Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable forkjoin subscribe types

I'm making 2 API requests calls with typed responses, combining them into a single Observable.forkJoin. I want to get both results in different typed variables.

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

How can I reach typed results in single subscribe response?

like image 408
Jorge Guerola Avatar asked Sep 18 '17 11:09

Jorge Guerola


People also ask

Does forkJoin subscribe?

forkJoin accepts a variable number of observables and subscribes to them in parallel.

What is return type of forkJoin?

Returns. Accepts an Array of ObservableInput or a dictionary Object of ObservableInput and returns an Observable that emits either an array of values in the exact same order as the passed array, or a dictionary of values in the same shape as the passed dictionary.

Is forkJoin deprecated?

forkJoin Improvements Moreover, there is one deprecation — forkJoin(a, b, c, d) should no longer be used; Instead, pass an array such as forkJoin([a, b, c, d]) .


2 Answers

Use es6 destructuring also you can add types if they dont automatically assigned

 Observable.forkJoin([ observableOrganization, observablePromotion])
        .subscribe(([org, prom]: [Organization, Promotion[]]) => {
            organization:Organization = org;
            promotions: Promotions[] = prom
        },
        error => {
            //error here
        });
like image 118
alexKhymenko Avatar answered Oct 08 '22 03:10

alexKhymenko


forkJoin will only return "nice" types, when the requests are explicitly declared as ObservalbleInput.

I personally prefer this syntax, using the destructing language feature:

const requests: [ObservableInput<Organization>, ObservableInput<Promotion[]>] = [observableOrganization, observablePromotion];
Observable.forkJoin(requests)
    .subscribe(
        ([organization, promotions]: [Organization, Promotion[]]) => {
            // use organization and promotions here
        },
        error => {
            // ...
        }
    );
like image 37
slartidan Avatar answered Oct 08 '22 04:10

slartidan