如何将第一个可观察量的结果用于下一个可观察量?



我有这个方法:

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可观察结果传递给$two可观察和$hree可观察结果?我可以在第一个switchMap上得到它。

你在switchMap上使用map来创建"resultSelector"。 switchMap 有一个 resultSelector 函数,可用于创建相同的效果,但这可能会在未来版本的 RxJS 中被弃用,而不是使用map,如下面的答案所示。您将有效地将oneResulttwoResult打包到对象或数组中,以便在第二个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));
}
}

使用switchMapresultSelector函数:

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,展示了此功能的实际效果。

希望对您有所帮助!

相关内容

最新更新