How to use forkjoin to return combined responses of two independent API calls in Angular


I have two independent api calls. Below is the code for two api calls:

public getLendingType(partyId: string): Observable<{ lendingType: string, partyId: string }> {
    return this.customerRepositoryService.getCustomer(partyId).pipe(
        map((customer: ICustomer) => {
          return { lendingType: customer.LendingType, partyId: partyId } ;

  private getPartyType(partyId: string): Observable<{ partyType: string}> {
    return this.partyRepositoryService.getParty(partyId).pipe(
      map((party: IParty) => {
        return  { partyType: party.PartyType };

As you can see both api call is independent from each other. At this point I want to use forkjoin to combine their responses and return the combined result. This is where I got stuck. The code I have written for this part is below:

  public getPartyTypeAndLendingType(partyId: string): Observable<{ partyType: string, lendingType: string, partyId: string }> {

        return forkJoin([this.getLendingType(partyId), this.getPartyType(partyId)]).subscribe ( result => {
            return { partyType: result[1].partyType, lendingType: result[0].lendingType, partyId: result[0].partyId }

but I think I am missing something for which still I am getting compiler error like the image below:

enter image description here

and hovering over the compiler error it showing below messages:

Type 'Subscription' is missing the following properties from type 'Observable<{ partyType: string; lendingType: string; partyId: string; }>': source, operator, lift, subscribe, and 3 more.ts(2740

How to achieve this and make this piece of code working?


Because you are calling .subscribe() your function returns a Subscription instead of an Observable.

To transform the result of the API calls use a .pipe() with map(). This way your function will return an Observable.

return forkJoin([
  map(result => 
    ({ partyType: result[1].partyType, lendingType: result[0].lendingType, partyId: result[0].partyId })     

Answered By – Tobias S.

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.