【发布时间】:2021-02-26 15:53:18
【问题描述】:
我在我的项目中使用 angular 10。 我在 ngOnInit 函数中嵌套了 HTTP 调用,如下所示:
ngOnInit(): void {
let communetyid;
this.route.data.subscribe(data => {
this.route.params.subscribe(params => {
if(data.category === "code")
{
this.dataService.getCode(params.code)
.subscribe(resp => { communetyid = resp.results.communityId });
}
else
{
communetyid = params.id
}
this.dataService.getCommunityById(communetyid)
.subscribe(response => { this.community = response.results;
///other http calls
})
})
})
})
正如您在上面的代码中看到的,dataService.getCommunityById 作为参数 communetyid 获取,communetyid 在 if 语句中获取值。由于在 communityid 获取值之前触发了异步 dataService.getCommunityById 函数,我在控制台中收到错误。
如何更改代码,当dataService.getCommunityById 被触发时,值 communetyid 将被初始化。
我知道我可以在dataService.getCode 的订阅中复制dataService.getCommunityById,但我想防止代码重复。
【问题讨论】:
-
您可以找到针对您的案例的详细解决方案以及通过 Http in this article 使用 RxJs 的常见示例
标签: angular typescript asynchronous rxjs