rxjs中如何做链序

新手上路,请多包涵

我想这样做:

 this._myService.doSomething().subscribe(result => {
  doSomething()
});
.then( () => dosthelse() )
.then( () => dosanotherthing() )

所以我想在承诺中链接 .then 。我将如何在 Rxjs 中做到这一点?

 this._myService.getLoginScreen().subscribe( result => {
      window.location.href = MyService.LOGIN_URL;
      /// I would like to wait for the site to load and alert something from       the url, when I do it here it alerts the old one
    });
   .then (alert(anotherService.partOfTheUrl())

getLoginScreen() {
  return this.http.get(myService.LOGIN_URL)
.flatMap(result => this.changeBrowserUrl())
.subscribe( result => //i want to do sth when the page is loaded//);
}

changeBrowserUrl(): Observable<any> {
return Observable.create( observer => {
window.location.href = myService.LOGIN_URL;
observer.next();
});
}

原文由 adam nowak 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 397
1 个回答

说明示例(2022 年 4 月)

该管道的顶部可以发出 n 个值(这意味着每次新值进入管道顶部时都会调用该链)。在这个例子中,n 等于 3。这是 observables 和 Promise 之间的关键区别。 Observables 可以随着时间的推移发出多个值,但 Promise 不能。

随后的链式流发出一个值(因此模仿承诺)。

 // Emit three values into the top of this pipe.
const topOfPipe = of<string>('chaining', 'some', 'observables');

// If any of the chained observables emit more than 1 value
// then don't use this unless you understand what is going to happen.
const firstObservable = of(1);
const secondObservable = of(2);
const thirdObservable = of(3);
const fourthObservable = of(4);

const addToPreviousStream = (previous) => map(current => previous + current);
const first = (one) => firstObservable.pipe(addToPreviousStream(one));
const second = (two) => secondObservable.pipe(addToPreviousStream(two));
const third = (three) => thirdObservable.pipe(addToPreviousStream(three));
const fourth = (four) => fourthObservable.pipe(addToPreviousStream(four));

// Pipeline of mergeMap operators, used for chaining steams together.
topOfPipe.pipe(
  mergeMap(first),
  mergeMap(second),
  mergeMap(third),
  mergeMap(fourth),
).subscribe(console.log);

// Output: chaining1234 some1234 observables1234

您也可以使用 concatMap 或 switchMap。它们都有细微的差别。请参阅 rxjs 文档以了解。

合并地图: https ://www.learnrxjs.io/learn-rxjs/operators/transformation/mergemap

concatMap: https ://www.learnrxjs.io/learn-rxjs/operators/transformation/concatmap

switchMap: https ://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap

原文由 Kevin Baker 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题