【发布时间】:2020-10-04 18:59:23
【问题描述】:
我有来自可观察对象的数据,我试图将其保存到变量中以在模板中使用,我可以看到在可观察对象范围内保存到 this.products 的数组或对象中返回的数据,但是,当我在执行 observable 后检查 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 时,它不会保存。所以“获取后”控制台日志只显示一个空数组。
【问题讨论】:
-
变量
this.products是异步赋值的。它不能被同步访问。任何依赖它的语句(如console.log)都必须在订阅中。 -
仅供参考,您应该不拥有那么多行禁用规则;编写规则想要的代码(生命周期接口,未使用的表达式)或为您要编写的内容(变量名)正确配置。
标签: arrays angular object observable