[英]How to make function to return Observable?
我是 rxjs 库的新手,并且在与库相关的一些事情上挣扎。
我有功能:
initData(code)
{
this.selectedLot = this.lots.find(x => x.id == code.Id);
this.dataService.getplan(code.Id)
.subscribe(response => {
this.plans = response.results;
this.selectedPlan = this.plans.find(x => x.id == code.homeId);
})
}
如您所见,该函数包含进行 http 调用的服务,并通过集合中的 id 进行一些选择。 函数 initData 需要返回 Observable。
我的问题是如何更改上面的函数以使其返回 Observable?
我可能在 initData 函数中有多个 http 请求:
initData(code)
{
this.selectedLot = this.lots.find(x => x.id == code.Id);
this.dataService.getplan(code.Id)
.subscribe(response => {
this.plans = response.results;
this.selectedPlan = this.plans.find(x => x.id == code.homeId);
})
this.userService.getUserData(code.userId, code.placeId)
.subscribe(resp=> { this.user = resp.results[0] });
this.userService.getAreaUrl(code.areaId)
.subscribe(resp=> { this.areaLogoUrl = resp.results[0] });
}
不要订阅可观察的,而只是返回它
initData(code) {
this.selectedLot = this.lots.find(x => x.id == code.Id);
return this.dataService.getplan(code.Id);
}
如果您想按顺序(从评论中)点击 api,请使用concatMap和tap运算符。
initData(code) {
return this.dataService.getplan(code.Id).pipe(
concatMap(e => this.userService.getUserData(code.userId, code.placeId))
.pipe(tap(resp => this.user = resp.results[0] )),
concatMap(e => this.userService.getAreaUrl(code.areaId))
.pipe(tap(resp => this.areaLogoUrl = resp.results[0] ))
)
}
您可以简单地返回Observable
。 您可以使用rxjs
运算符对数据执行各种转换
initData(code)
{
this.selectedLot = this.lots.find(x => x.id == code.Id);
return this.dataService.getplan(code.Id).pipe(
tap(response => {
this.plans = response.results;
this.selectedPlan = this.plans.find(x => x.id == code.homeId);
})
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.