可观察的forkjoin订阅类型

时间:2017-09-18 11:52:58

标签: angular typescript rxjs observable

我正在使用类型化响应进行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 => {
            // ...
        }
    );

如何在单个订阅响应中获得键入的结果?

2 个答案:

答案 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 => {
            // ...
        }
    );