(Angular 2/4/5/6)具有多个http请求的嵌套订阅方法



我需要在订阅方法中调用一个订阅方法。

在第一个订阅方法中,它向我返回一个设备ID,该设备ID随后用于第二个订阅方法。

result=[];
idArray=[2,4];
this.subscription =
this.quoteService.get(this.quoteid) //first api call
.subscribe((quote: Quote) => {   
this.deviceid = quote["deviceid"]; 
this.faultService.get(this.deviceid) //second api call
.pipe(first())
.subscribe((faultGroup: FaultGroup[]) => {
faultGroup.forEach(({ faults }) => {
//execute logic for 2nd subscription
if (faults) {
faults
.filter(
({ id }) => this.idArray.indexOf(id) > -1,
)
.forEach(fault => this.result.push(fault.name));
}
//end of logic
});
});
subscription.unsubscribe();
}
});

有人能教我如何使用flatMap/switchMap来避免使用嵌套订阅吗?感谢你的帮助!

这里的要求是从第二个API返回结果,只是要调用第二个API,需要第一个的结果。为此,switchMap()最适合您。按照代码中的说明使用它。

this.subOb = this.quoteService.get(this.quoteid) //first api call
.pipe(switchMap((quote: Quote) => {
// result of first API call here
this.deviceid = quote["deviceid"];
// you need to return the second observable from inside the switcMap
// and this will only be executed after the first Observable(first API call) is finished
return this.faultService.get(this.deviceid) //second api call
// need some mode logic after second API call is done? call first()?
// map the result with a pipe
.pipe(map(secondData) => { 
// If you aren't manipulating the data 
// to be returned, then use tap() instead of map().
return data;
})
}))
.subscribe((data) => {
// only one subscription is required.
// this will have data from second API call
})

对于Subscriptions,使用ngOnDestroy()挂钩到unsubcribe()。我看到您正在将订阅分配给一个变量,并可能使用相同的值来取消订阅。如果你的Observable多次发射(我认为它没有(,那么在第一次发射subscribe()时,"订阅"变量将被取消定义。

ngOnDestroy() {
if (this.subOb) {
this.subOb.unsubscribe();
}
}

请在此处查看示例:https://stackblitz.com/edit/swicthmap?file=src%2Fapp%2Fapp.component.ts

它包含切换映射的两个实现,分析这两个实现并使用任何套件。

最新更新