angular - 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?
解决方案
使方法返回 Observable 或直接使用服务。
getNewShoppingCart(): Observable<ItemsType> {
return this.serverService.getShoppingCart()
}
在组件中创建一个 BehaviorSubject 字段。
shopingCart = new BehaviorSubject();
在 ngOnInit 上放一些数据:
shopingCart.next(this.getNewShoppingCart())
在组件中使用异步管道指向 shopingCart
从您需要的 BehaviorSubject 中获取值,如下所示:
shopingCart.getValue()
推荐阅读
- c++ - 编译时 C++ 函数检查是否所有模板参数类型都是唯一的
- python - 基数为 10 的 int() 的无效文字:b'13 18:33:25'
- django - 使用两个表或具有多行的单个表?
- python - 使用包含大量数据的 python 生成器
- java - 如何访问 Android 中的缓存以进行检测测试?
- javascript - 每次重新加载网页时如何重新加载视频
- javascript - 拓扑已关闭
- javascript - 如何从文件系统访问 api window.showDirectoryPicker() 获取选定的目录路径
- javascript - 使用 xml dom 解析器处理 angular http post 响应数据
- python - 在 Python 中迭代大量数据的有效方法