首页 > 解决方案 > Angular component waiting for service to recive data from API

问题描述

Hi in my app I have a service and a `component'.

My service is reciving data from API:

getNewShoppingCart() {
  this.serverService.getShoppingCart().subscribe(
    (data) => {
      this.basket.boughtItems = data;
      });
}

and my component has got some methods that uses the object recived by service.

Since the component is rendered before the service gets the data I have some errors in the console.

How can I force the component to wait until the data is loaded?

标签: angularpromiseangular-services

解决方案


使方法返回 Observable 或直接使用服务。

getNewShoppingCart(): Observable<ItemsType> {
  return this.serverService.getShoppingCart()
}

在组件中创建一个 BehaviorSubject 字段。

shopingCart = new BehaviorSubject();

在 ngOnInit 上放一些数据:

shopingCart.next(this.getNewShoppingCart())

在组件中使用异步管道指向 shopingCart

从您需要的 BehaviorSubject 中获取值,如下所示:

shopingCart.getValue()

推荐阅读