我有这个方法:
zip(
this.$one.getOne(id)
.pipe(switchMap(oneResult => {
return this.$two.getTwo(oneResult.id)
}))
.pipe(switchMap(twoResult => {
// Here I Would like to use the **oneResult** as argument to the $three observable too.
return this.$three.getThree(oneResult.id)
})),
this.$four.getFour()
).subscribe(zipResult => {
[getTwoResult, getThreeResult]
}
如何将 $one
Observable 结果传递给 $two
Observable 和 $hree
observable?我可以在第一个 switchMap 上获取它。
最佳答案
您可以在 switchMap
上使用 map
创建“resultSelector”。 switchMap有一个可用于创建相同效果的 resultSelector 函数,但在 RxJS 的 future 版本中可能会弃用它,以代替使用 map
,如下面的答案所示。您可以有效地将 oneResult
和 twoResult
打包到一个对象或数组中,以便在第二个 switchMap
中使用。您可以根据需要继续这样做。它看起来像这样(我添加了延迟来模拟 API 调用):
import { Component } from '@angular/core';
import { Observable, of, zip } from 'rxjs';
import { map, switchMap, delay } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
getOne(id: string): Observable<string> {
return of('foo').pipe(delay(1000));
}
getTwo(id: string): Observable<string> {
return of('bar').pipe(delay(1000));
}
getThree(id: string): Observable<string> {
return of('baz').pipe(delay(1000));
}
getFour(id: string): Observable<string> {
return of('foobar').pipe(delay(1000));
}
ngOnInit(): void {
zip(
this.getOne('foo').pipe(
switchMap(oneResult =>
this.getTwo(oneResult).pipe(
map(twoResult => ({ oneResult, twoResult }))
)
),
switchMap(oneTwoResult => {
console.log(oneTwoResult);
return this.getThree(oneTwoResult.oneResult);
})
),
this.getFour('foobar')
)
.subscribe(result => console.log(result));
}
}
使用switchMap
的resultSelector
函数:
zip(
this.getOne('foo').pipe(
switchMap(oneResult =>
this.getTwo(oneResult),
(oneResult, twoResult) => ({ oneResult, twoResult })
),
switchMap(oneTwoResult => {
console.log('oneTwoResult: ', oneTwoResult);
return this.getThree(oneTwoResult.oneResult)
})
),
this.getFour('foobar')
)
.subscribe(result => console.log(result));
这是一个StackBlitz显示此功能的实际效果。
希望对您有所帮助!
关于angular - 如何将第一个可观察对象的结果用于下一个可观察对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118806/