我想这样做:
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 许可协议
说明示例(2022 年 4 月)
该管道的顶部可以发出 n 个值(这意味着每次新值进入管道顶部时都会调用该链)。在这个例子中,n 等于 3。这是 observables 和 Promise 之间的关键区别。 Observables 可以随着时间的推移发出多个值,但 Promise 不能。
随后的链式流发出一个值(因此模仿承诺)。
您也可以使用 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