Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何访问在angular4的同一类中声明的服务响应中的变量?_Angular_Angular Cli - Fatal编程技术网

如何访问在angular4的同一类中声明的服务响应中的变量?

如何访问在angular4的同一类中声明的服务响应中的变量?,angular,angular-cli,Angular,Angular Cli,在登录服务调用的响应中,我无法访问或为标志变量赋值。但是,我可以在login方法中访问它,在该方法中,我将其值更新为true。 我在登录服务中也面临同样的问题 Bind(这个)可能会帮助您解决问题 import {Component, OnInit} from '@angular/core'; import {LoginService} from "../../services/login.service"; import {LoginUser} from "../../services/mod

在登录服务调用的响应中,我无法访问或为标志变量赋值。但是,我可以在login方法中访问它,在该方法中,我将其值更新为true。 我在登录服务中也面临同样的问题

Bind(这个)可能会帮助您解决问题

import {Component, OnInit} from '@angular/core';
import {LoginService} from "../../services/login.service";
import {LoginUser} from "../../services/model";

@Component({
selector: 'login-component',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {
private user: LoginUser = new LoginUser();
public flag : boolean = false;
constructor(private loginService: LoginService) {}

login(): void {
  this.flag = true;
  this.loginService.login(this.user).then(function (response) {
  console.log(this.flag);
  });
 }
}

Angular使用Typescript,默认情况下,它具有ES6的大部分功能。如果要将函数作为回调参数传入,请不要使用
function(){}

使用此可为您提供词汇

login(): void {   
    this.flag = true;   
    this.loginService.login(this.user).then((response)=>{ 
        console.log(this.flag);   
    });  
} }

谢谢@CozyAzure。它起作用了。不幸的是,由于我的账户信用度低,公众形象无法看到我的账户。谢谢你的帮助。我们不能同时使用ES6和bind函数。我们也可以使用bind函数来解决它。不过,用下面的方法。login():void{this.flag=true;this.loginService.login(this.user)。然后(function(){console.log(this.flag);}.bind(this));}理解。不需要使用bind(这个)。Angular使用打字脚本@CozyAzure已经回答了。更新了我的答案。
login(): void {
    this.flag = true;
    this.loginService.login(this.user).then((response) => {
        console.log(this.flag);
    });
}