我的 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 调用链接到另一个指示 API 是否准备好调用的 readySource
Observable,而不是像往常一样返回 http.get
Observable (它实际上检查后台数据同步作业是否已完成)。
我如何将这两个 Observable 链接在一起,以便仅在 readySource
推送特定值时调用 HTTP 调用,例如“准备好”了吗?
(请注意,vanilla flatMap/selectMany 并不能完全满足此处的要求,因为我需要等到第一个 Observable 推送特定值后才能调用第二个。)
最佳答案
我会将 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');
});
}
}
关于typescript - 在 Angular 2 中链接 RxJs Observables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180607/