javascript - 从可观察同步获取数据。 Angular

标签 javascript angular typescript rxjs observable

我正在尝试从可观察的数据中获取数据。在 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/

相关文章:

javascript - Angular 6 显示或隐藏列表项

javascript - Typescript 返回一个对对象进行操作的数组

javascript - WebSocketGateway 中的 WsException 不起作用

typescript - Visual Studio代码无法正确踩入TypeScript代码

javascript - jQuery .each 和 setTimeout 不能很好地协同工作

authentication - 无法使用 Auth0 获取委托(delegate) token

angular - 如何在 Angular 4+ 上使用 cookie 来获取和发布

javascript - 在 Electron 中,如何从完整文件名上传文件

javascript - 我可以动态更改 Facebook Like 按钮的 'likeable' 对象吗?

JavaScript 转换用户输入