Reputation: 41902
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;
}
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).
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"?
(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.)
Upvotes: 4
Views: 2404
Reputation: 202306
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');
});
}
}
See this plunkr: https://plnkr.co/edit/yZL1wRw7GYhUkkhnL9S0?p=preview
Upvotes: 6