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

时间:2017-07-12 03:49:58

标签: angular angular2-routing

在组件中使用未定义变量但在模板中定义

Im noobie:p

当我试图在控制台中获取this.authService.queue_start时,我得到了未定义



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);
   }
}




1 个答案:

答案 0 :(得分:0)

问题是http.get返回一个observable,因此你的代码将在异步中运行..这些行在这里:

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)变成一个返回承诺的新方法。

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会得到您想要的结果。

这是你的班级现在的样子:

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> {
    //....
}

<强> --------------- UPDATE ------------------

要使用您获得的结果,您可以像这样使用它:

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);
        }
    });
}