![](/img/trans.png)
[英]How to wait for a observable method to finish before proceeding in Angular 2
[英]How to wait for observable to finish? Angular 2
我有多个调用,需要等待所有调用完成,然后才能路由到不同的页面。 我遇到的问题是,通常我一直在嵌套 Web 服务调用,但对于这种情况,我有单独的调用,这些调用可能会或可能不会根据用户的输入进行调用。 在路由到新页面之前,如何等待所有可能会或可能不会被调用的调用。
submitButton_Clicked() {
this.busy = this.service.call1() // must be called
.first().subscribe(
if (success){
// **Logic to decide if call 2 is needed**
...
this.busy = this.service.call2() // might be called
.first().subscribe();
// **Logic to decide if call 3 is needed**
...
this.busy = this.service.call3() // might be called
.first().subscribe();
this.router('route'); // should route after all potential calls
}
);
}
我是 observables 的新手,所以我不确定这样做的最佳方法是什么。 谢谢您的帮助!
你可以使用 flatMap
let Observable = Rx.Observable;
let f = Observable.of(20).delay(1000);
let g = f.map(x => x*x)
.flatMap(x => Observable.of(x + 100));
g.subscribe(console.log);
/**
* Rx.Observable.prototype.flatMap
* and Rx.Observable.prototype.selectMany
* are equivalent.
*/
let h = f.map(x => x*3)
.delay(1000)
.flatMap(x => Observable.of(x + 100));
h.subscribe(console.log);
https://jsbin.com/vokofug/edit?js,console,output
或连接或合并:
concat() 流将首先打印 source1 中的所有值,并且仅在 source1 完成后才开始打印 source2 中的值。
merge() 流将在收到来自 source1 和 source2 的值时打印它们:在从第二个流发出值之前,它不会等待第一个流完成。
http://codepen.io/SitePoint/pen/PzKdVQ
'use strict';
const source1 =
Rx.Observable.interval(100)
.map(val => `Source 1: ${val}`)
.take(5);
const source2 =
Rx.Observable.interval(100)
.map(val => `Source 2: ${val * 10}`)
.take(5);
const concat_table = $('#concat-table-body'),
merge_table = $('#merge-table-body');
source1
.concat(source2)
.subscribe(value => {
const row = document.createElement('tr');
row.innerHTML = value;
// Source 1 values populate BEFORE Source 2
concat_table.append(row);
});
source1
.merge(source2)
.subscribe(value => {
const row = document.createElement('tr');
row.innerHTML = value;
// Source 1 values INTERLEAVE with Source 2
merge_table.append(row);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.