【问题标题】:How to wait for observable to finish? Angular 2如何等待 observable 完成?角 2
【发布时间】:2017-02-06 10:46:08
【问题描述】:

我正在拨打多个电话,需要等待所有电话都完成,然后才能转到其他页面。我遇到的问题是,通常我一直在嵌套 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 的新手,所以我不确定最好的方法是什么。谢谢您的帮助!

【问题讨论】:

标签: angular typescript rxjs observable


【解决方案1】:

你可以使用 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);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2018-08-06
    • 1970-01-01
    • 2017-09-20
    • 2018-09-05
    • 2021-11-16
    相关资源
    最近更新 更多