在Angular 2中链接RxJs可观察对象 [英] Chaining RxJs Observables in Angular 2
问题描述
我的Angular 2应用程序中有一个TypeScript函数,该函数返回一个Observable,以将Web API数据推回给使用者,如下所示:
I've got a TypeScript function in my Angular 2 app that returns an Observable, to push web API data back to the consumer, something like this:
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是否已准备好调用(它实际上检查后台数据同步作业是否已完成) ).
However, rather than returning the http.get
Observable as normal, I need to chain this HTTP call to another readySource
Observable that indicates whether the API is ready to call (it actually checks whether a background data sync job has finished).
我如何将这两个Observable链接在一起,所以仅在readySource
推送特定值(例如准备好了吗?"
How can I chain these two Observables together, so the HTTP call is only invoked once the readySource
pushes a particular value, e.g. "ready"?
(请注意,vanilla flatMap/selectMany并不能完全满足这里的要求,因为我需要等到第一个Observable推入特定值后再调用第二个.)
(Note that vanilla flatMap/selectMany doesn't quite meet the requirement here, because I need to wait until the first Observable pushes a specific value before invoking the second.)
推荐答案
我将filter
运算符与flatMap
运算符混合在一起.以下示例描述了当用户填写特定值(此处为就绪")时如何触发请求:
I would mix the filter
operator with the flatMap
one. The following sample describes how to triggers the request when the user fills a specific value ('ready' here):
@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');
});
}
}
请参阅以下代码: https://plnkr.co/edit/yZL1wRww7GYhUkkhnL9S0?p=preview
这篇关于在Angular 2中链接RxJs可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!