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?
forkJoin accepts a variable number of observables and subscribes to them in parallel.
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.
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]) .
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
});
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 => {
// ...
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With