2016-05-12 67 views
1

我有我的角2的應用程序一個打字稿函數返回一個可觀察到,推動網絡API數據傳回給消費者,這樣的事情:鏈接RxJs觀測量的角2

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

然而,相當比通常返回http.get Observable,我需要鏈接此HTTP調用到另一個readySource Observable,它指示API是否準備好調用(它實際上檢查背景數據同步作業是否已完成)。

如何將這兩個觀察值鏈接在一起,因此只有在readySource推入特定值時纔會調用HTTP調用,例如, 「準備」?

(請注意,香草flatMap /沒有的SelectMany不太符合這裏的要求,因爲我需要等待,直到第一個可觀測調用推前一秒一個特定的值。)

回答

5

我會混合filter操作flatMap之一。下面的示例介紹瞭如何當用戶填寫一個特定的值(「準備好」在這裏)觸發請求:

@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