如果他们是独立的,我可以做类似forkJoin的事情来获得结果。 但是由于事实,我只有在得到A后才能服用B,所以我有点挣扎。 我尝试过switchMap,但似乎也无法正常工作。
所以我要实现的是:
将A和B合并为结果C
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return this.service.getB(response.id);
}
),
map(result => this.getData(result)) // here i want A and B thogether so result should contain A and B
);
}
目前我有点迷路了。 问候 奥利弗
答案 0 :(得分:0)
您可以这样做:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return this.service.getB(response.id).pipe(
map(responseB => ({responseA: response, responseB})),
);
}),
map(result => this.getData(result)) // result already have responseA & responseB
);
}
或者这个:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return this.service.getB(response.id).pipe(
map(responseB => this.getData(...)), // you have access to response and responseB here
);
}),
);
}
答案 1 :(得分:0)
尝试使用zip
方法来合并两个Observable的两个结果:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return Observable.zip(
this.service.getB(response.id),
of(response)
);
return this.service.getB(response.id);
})),
.subscribe(([resA, resB]) => {
console.log('resA', resA);
console.log('resB', resB);
}
zip
通过 指定的功能并根据以下内容为每个组合发出单个项目 该功能的结果
答案 2 :(得分:0)
您可以使用switchMap
(resultSelector)的第二个参数来组合结果:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA()
.pipe(
switchMap(response => this.service.getB(response.id), (a, b) => this.getData({a, b})),
);
}