在组件中使用它时得到未定义的变量,但它在模板中定义

Got undefined variable when using it in the component but it is defined in the template

在组件中使用它时得到未定义的变量,但它在模板中定义

我是菜鸟:p

当我尝试在控制台中获取 this.authService.queue_start 时,我得到了 undefined

public queue_start: string;
constructor(private http: Http, private authService: AuthService, private router: Router) {
const token = localStorage.getItem('token');
if(token){
        this.http.get('api/v1/user?token='+ token)
          .subscribe(
              response => {
                  this.authService.dataa = response;
                  this.authService.queue_start = this.authService.dataa.json().queue_start;
                  },
              error => console.log(error),
          );
    }



if(this.authService.queue_start == "1"){
     console.log(this.authService.queue_start,"queue_start = 1");
   }else {
  console.log(this.authService.queue_start);
   }
}

问题是 http.get return 一个可观察对象,因此您的代码将 运行 异步。这些行在这里:

if(this.authService.queue_start == "1"){
   console.log(this.authService.queue_start,"queue_start = 1");
}else {
   console.log(this.authService.queue_start);
}

将在 this.http.get('api/v1/user?token='+ token) 给出结果之前执行。

为了解决这个问题,您必须将 this.http.get('api/v1/user?token='+ token) 变成一个 return 承诺的新方法。

getData(token): Promise<any> {
    return new Promise(resolve => {
        this.http.get('api/v1/user?token='+ token)
            .subscribe(
                response => {
                    resolve(response.json().queue_start);
                },
                error => console.log(error));
    });
}

要在 constructor 中调用此异步方法如下所示:

if(token){
    this.getData(token).then(queueStart => console.log(queueStart));
}

现在您应该能够看到 queueStart 会得到您想要的结果。

这就是您的 class 现在的样子:

public queue_start: string;

constructor(private http: Http, private authService: AuthService, private router: Router) {
    const token = localStorage.getItem('token');
    if(token){
        this.getData(token).then(queueStart => console.log(queueStart));
    }
}

getData(token): Promise<any> {
    //....
}

----------------更新-----------------

要使用你得到的结果,你可以这样使用它:

if(token){
    this.getData(token).then(queueStart => {
        this.authService.queue_start = queueStart;
        if(this.authService.queue_start == "1"){
            console.log(this.authService.queue_start,"queue_start = 1");
        }else {
            console.log(this.authService.queue_start);
        }
    });
}