我有一个文件,我用REST服务编写整个连接的代码,它可以工作。
从另一个文件中,我正在执行以下行(一切正常)
import mypackage.xyz.Mung.*;
要访问我使用 this.baseService.getCars(ID)
.subscribe(cars=> this.cars= cars);
的回复值。例如:HTML
现在,我想通过*ngIf="cars"
访问变量:
Javascript
但我得到了this.baseService.getCars(ID)
.subscribe(cars=> this.cars= cars);
console.log(this.cars)
,但我可以undefined
访问。我知道这是一个问题,但我应该怎么做呢?哪个变量确实包含变量?
答案 0 :(得分:3)
这些代码行的执行顺序不是你想象的那样。
要在控制台中查看汽车,请将功能更改为:
string
答案 1 :(得分:1)
您需要将console.log放在 subscribe
中 this.baseService.getCars(ID)
.subscribe(
cars=> {
this.cars= cars;
console.log(this.cars);
},
error => {
console.log(error);
}
);
答案 2 :(得分:1)
订阅是异步的,就像Promise一样,但不是Promise所以,当你执行代码时,会触发订阅,然后是控制台日志。但是当console.log正在执行时,订阅仍在运行,这就是你未定义的原因。
您可以在subscribe
中的回调函数中执行console.logthis.baseService
.getCars(ID)
.subscribe(cars=> {
this.cars = cars
console.log(this.cars)
});
另一种解决方案是使用async / await。您不能直接使用async / await与订阅,因为IT并不是一个承诺。幸运的是,Observers可以转换为Promise。
因此,在您的服务中,您可以返回一个承诺,如下:
getCars() {
// your service stuff
return this.api.get(url).toPromise().then( res => res.data); // This is the important part.
}
然后,在您的组件中,使用async / await:
进行调用async yourFunction() {
this.cars = await this.baseService.getCars(ID);
console.log(this.cars);
}
现在,您可以在this.cars
getCars()
希望这会对你有所帮助。