我正在使用类型化响应进行2次API请求调用,将它们合并为一个Observable.forkJoin
。我希望在不同的类型变量中得到两个结果。
var observableOrganization: Observable<Organization> = this.getOrganizationDetails();
var observablePromotion: Observable<Promotion[]> = this.getPromotions();
Observable.forkJoin([ observableOrganization, observablePromotion])
.subscribe(
response => {
organization: Organization = response[0];
promotions: Promotion[] = response[1];
},
error => {
// ...
}
);
如何在单个订阅响应中获得键入的结果?
答案 0 :(得分:12)
使用es6 destructuring还可以添加类型,如果他们不自动分配
Observable.forkJoin([ observableOrganization, observablePromotion])
.subscribe([org, prom]: [Organization, Promotion[]]) => {
organization:Organization = org;
promotions: Promotions[] = prom
},
error => {
//error here
});
答案 1 :(得分:2)
forkJoin
仅在将请求显式声明为ObservalbleInput
时才返回“ nice”类型。
我个人更喜欢使用destructing语言功能使用以下语法:
const requests: [ObservableInput<Organization>, ObservableInput<Promotion[]>] = [observableOrganization, observablePromotion];
Observable.forkJoin(requests)
.subscribe(
([organization, promotions]: [Organization, Promotion[]]) => {
// use organization and promotions here
},
error => {
// ...
}
);