簡體   English   中英

在Angular 2中鏈接RxJs Observables

[英]Chaining RxJs Observables in Angular 2

我的Angular 2應用程序中有一個TypeScript函數,它返回一個Observable,將Web API數據推送回消費者,如下所示:

public getApiData(): Observable {
    let readySource = Observable.from('no', 'no', 'ready');
    let dataSource = http.get('api/getData');
    // ... magic here
    return chainedObservable;
}

但是,我不是像http.get一樣返回http.get Observable,而是需要將此HTTP調用鏈接到另一個readySource Observable,指示API是否已准備好調用(它實際上檢查后台數據同步作業是否已完成)。

如何將這兩個Observable鏈接在一起,因此只有在readySource推送特定值(例如“ready”)后才會調用HTTP調用?

(注意,vanilla flatMap / selectMany在這里並不完全符合要求,因為我需要等到第一個Observable在調用第二個之前推送一個特定的值。)

我會將filter操作符與flatMap操作符混合。 以下示例描述了當用戶填寫特定值(此處為“ready”)時如何觸發請求:

@Component({
  selector: 'my-app',
  template: `
    <input [ngFormControl]="ctrl"/>
    <button (click)="onClick()">Click</button>
  `
})
export class AppComponent {
  constructor(private http:Http) {
    this.ctrl = new Control();
    let readySource = this.ctrl.valueChanges.filter((val) => val === 'ready');
    readySource.flatMap(() => http.get('data.json')).subscribe(() => {
      console.log('test');
    });
  }
}

看到這個plunkr: https ://plnkr.co/edit/yZL1wRw7GYhUkkhnL9S0 p = preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM