angular - 我如何在我的服务中等待我的方法的结果?
问题描述
我的服务中有这种方法。
get trucks() {
if (!this.cache$) {
this.cache$ = this.requestAvailableTrucks().pipe(
shareReplay(CACHE_SIZE)
);
}
return this.cache$;
}
private requestAvailableTrucks() : Observable<Array<any>> {
return this.http.get<any>(API_ENDPOINT_TRUCKS).pipe(
map(response => response.value)
);
}
在我的应用程序组件中,我需要将我的属性初始化为 requestAvailableTrucks 调用的结果。之后,我需要根据来自后端的结果做一些逻辑。但问题是我不知道如何等待这种方法。
当我尝试
ngOnInit() {
this.locations = this.truckService.trucks;
... The other logic ...
}
其他逻辑不要等待我的服务中的方法结束。
唯一可以做的是订阅方法,并将代码放在那里,但我需要在我的服务中包含我的逻辑并像这样从我的 ts.file 调用它
解决方案
您可以简单地使用 subscribe 以便它等待响应。
ngOnInit() {
this.truckService.trucks.subscribe(trucks => {
this.locations = trucks;
});
}
推荐阅读
- javascript - 如何使邮件正文超过 255 个字符?
- aws-lambda - SNS 消息多次触发对 Lambda 函数的调用(处理过程中没有错误/超时)
- javascript - javascript中的对象操作数组
- ios - iOS swift3中的安全文件夹
- svg - 如何将 SVG 转换为可以保存在后端的 JSON,然后再次调用 JSON 并将其转换为 SVG
- ios - 无法对推送通知自定义按钮执行操作
- python - LeetCode 最长回文子序列问题的“超出时间限制”
- react-native - 带有底部标签栏导航的 React-native-router-flux 导航俱乐部抽屉
- intellij-idea - 隐藏一些注释
- javascript - Safari - WebInspector 网络选项卡 - 尝试加载资源时出错