在组件中使用未定义变量但在模板中定义
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);
}
}

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