我有一个文件,我用REST服务编码我的整个连接,而且它可以工作。
在另一个文件中,我正在执行以下行(everything works)
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
,但我可以通过HTML
访问。我知道这是个问题,但我该怎么做呢?哪个变量包含变量?
发布于 2018-01-08 08:33:03
这些代码行的执行顺序不是您所认为的那样。
若要查看控制台中的汽车,请将功能更改为:
this.baseService.getCars(ID)
.subscribe(cars=>{
this.cars= cars;
console.log(this.cars);
});
发布于 2018-01-08 08:38:27
您需要将console.log放在订阅中
this.baseService.getCars(ID)
.subscribe(
cars=> {
this.cars= cars;
console.log(this.cars);
},
error => {
console.log(error);
}
);
发布于 2018-01-08 08:50:17
订阅是异步的,就像承诺一样,但不是承诺,因此,当您执行代码时,会触发订阅,然后是控制台日志。但是当console.log执行时,订阅还在运行,所以这就是为什么您没有定义。
您可以在订阅中的回调函数中执行console.log。
this.baseService
.getCars(ID)
.subscribe(cars=> {
this.cars = cars
console.log(this.cars)
});
另一种解决方案是使用异步/等待。您不能直接与订阅一起使用异步/等待,因为这不是一个承诺。幸运的是,观察者可以转换成承诺。
因此,在您的服务中,您可以返回一个承诺,如:
getCars() {
// your service stuff
return this.api.get(url).toPromise().then( res => res.data); // This is the important part.
}
然后,在您的组件中,使用异步/等待调用它:
async yourFunction() {
this.cars = await this.baseService.getCars(ID);
console.log(this.cars);
}
现在您可以在this.cars
之后记录getCars()
希望这能帮到你。
https://stackoverflow.com/questions/48154259
复制