我正在尝试从可观察的数据中获取数据。在 subscribe()
方法中我可以访问这些数据。但是将响应传输到全局变量是行不通的。我怎样才能做到这一点?
服务:
getProducts():Observable<IProduct[]>{
return <Observable<IProduct[]>> this.db.collection('products').valueChanges();
}
组件:
products!: IProduct[];
constructor(private dataService: DataService){}
ngOnInit(): void {
this.dataService.getProducts().subscribe(response => {
console.log(response); // return data
this.products = response;
})
console.log("products: ", this.products) // return undefined
setTimeout(() => {
console.log("products: ", this.products) // return data
},1000)
}
我尝试在 html 中显示数据*ngFor="let item of (products | async)"
但它不起作用
最佳答案
您的console.log将返回未定义,因为它是在订阅完成之前执行的。另外,当您已经订阅时,您不需要在 html 中使用 async 关键字。所以你必须选择:
this.dataService.getProducts1().subscribe(response => {
console.log(response); // return data
this.products = response;
});
And in html:
*ngFor="let item of products"
或者你可以在html中使用observable和async关键字:
products: Observable<IProduct[]>;
var products = this.dataService.getProducts();
And in html:
*ngFor="let item of (products | async)"
如果您需要更好地理解 setTimeout 中为何有数据,请研究 Angular 中的 Microtask 和 Makrotasks 及其执行顺序。
关于javascript - 从可观察同步获取数据。 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75731965/