创建一个回放主题:
const sub = new ReplaySubject(3);
然后打电话
this.getProject(1).pipe(
tap(project => sub.next(project)),
switchMap(project => this.getSites(1)),
tap(sites => sub.next(sites)),
switchMap(sites => this.getPersons(sites[0].id)),
tap(person => sub.next(person))
);
您的回放主题将包含作为第一个值的项目,作为第二个值的站点,作为第三个值的人。
您可以使用combineLatest 格式和BehaviorSubject。
const obs = new BehaviorSubject([]);
const add = val => obs.pipe(
take(1),
map(v => ([...v, val]))
).subscribe(v => obs.next(v));
this.getProject(1).pipe(
tap(project => add(project)),
switchMap(project => this.getSites(1)),
tap(sites => add(sites)),
switchMap(sites => this.getPersons(sites[0].id)),
tap(person => add(person))
);
这一次,返回的值将是一个包含所有值的数组。
最后,您可以使用复杂的语法来连接它们,而无需使用主题。
this.getProject(1).pipe(
switchMap(project => this.getSites(1).pipe(map(sites => ([project, sites])))),
switchMap(([project, sites]) => this.getPersons(sites[0].id).pipe(map(person => ([project, sites, map])))),
);