我有一个来自可观察对象的数据,我试图保存到一个变量中以供模板使用,我可以看到数据在一个数组或对象中返回,我将其保存到可观察对象的范围内的this.products中,但是当我在执行可观察对象后检查this.products时,它显示为一个空数组。这是我使用的代码:在我的组件中:
title = 'ngProducts';
newProduct: any;
products: any = [] ;
selectedProduct: any;
// tslint:disable-next-line:variable-name
constructor(private _httpService: HttpService) { }
// tslint:disable-next-line:use-lifecycle-interface
ngOnInit() {
this.newProduct = {details: '', category: '', brand: ''};
// tslint:disable-next-line:no-unused-expression
this.selectedProduct;
}
getProductsFromService() {
const observable = this._httpService.getProducts();
// observable.subscribe(data => console.log('this is the observable data: ', data));
observable.subscribe(data => this.products = data);
console.log('this is after fetching products: ', this.products);
}
当我在控制台上记录可观察对象中的数据时,我得到了对象数组,但是当我尝试将其保存到this.products时,它并没有保存。因此,“获取后”控制台日志只显示一个空数组。
发布于 2020-10-04 19:14:33
observable的值在订阅中异步返回,而您尝试在返回值之前访问它。若要控制日志“获取值后”,请将其移动到订阅中。
getProductsFromService() {
const observable = this._httpService.getProducts();
observable.subscribe(data => {
this.products = data,
console.log('this is after fetching products: ', this.products);
});
}
发布于 2020-10-04 19:11:03
observable是异步的,这意味着subscribe()中代码的执行只有在HTTP调用完成后才会运行,而下面的console.log会立即运行。这意味着在执行console.log之前,行this.products = data行不会运行。
除此之外,代码看起来还不错,那么您还会遇到什么问题呢?你收到一个错误是因为你期望在前端有产品吗?你可以在前端添加一个*ngIf="products.length>0“来解决这个问题。
https://stackoverflow.com/questions/64198688
复制