21

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?

slartidan
  • 20,403
  • 15
  • 83
  • 131
Jorge Guerola
  • 2,072
  • 1
  • 16
  • 18
  • By "typed" you mean eg. this `Observable`? Or you want to merge the results? – martin Sep 18 '17 at 12:00
  • I don't want the merged results, I prefer separated types. – Jorge Guerola Sep 18 '17 at 12:01
  • I don't understand what you want to achieve or what doesn't work to be honest... – martin Sep 18 '17 at 12:02
  • in the .subscribe((response)) , the response type is Organization[] by default. This is wrong, I made 2 api calls which gives me 2 different types(Organization and Promotion[]), not Organization[] – Jorge Guerola Sep 18 '17 at 12:06
  • 2
    This is what you're doing https://github.com/ReactiveX/rxjs/blob/master/src/observable/ForkJoinObservable.ts#L23, it returns `Observable<[Organization, Promotion[]]>` – martin Sep 18 '17 at 12:16

2 Answers2

32

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
        });
alexKhymenko
  • 5,450
  • 23
  • 40
8

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 => {
            // ...
        }
    );
slartidan
  • 20,403
  • 15
  • 83
  • 131
  • Isn't this rather due to the fact that you're explicitly typing your subscribe value here by doing : [Organization, Promotion[]. I didn't get this working in any case. – rumblefx0 Jul 05 '19 at 12:27
  • @rumblefx0 Are you sure, you used `ObservableInput` for *all* requests? It worked for me quite well. – slartidan Jul 05 '19 at 14:02
  • Hmm, can you show how you instantiate observableOrganization & observablePromotion please? – rumblefx0 Jul 09 '19 at 07:25