Skip to content
Advertisement

How to merge two API response array in one array and returns data Angular 8

i am calling two different service and getting difrent response. but i want to build one common table after arranging the response of both the service.

below is my service

getUsersForAdmin() {
    this.budgetaryUnitService.getUserList('Budget Administrator').subscribe(response => {
      this.adminData = response;
      this.getUsersForViewer();
    });
  }

   getUsersForViewer() {
    this.budgetaryUnitService.getUserList('Budget Viewer').subscribe(response => {
      viewerData = response;
      this.buildData(viewerData);
      this.buildRolesTable(response);
    });
  }



  buildData(this.adminData,viewerData){
    console.log(this.adminData,"Admindata");
    console.log(viewerData,"viewerData");
  }

i am getting below response in AdminData.

var adminData = {
  "limit": 10,
  "start_offset": 0,
  "size": 2,
  "response": [
    {
      "userid": "mabasore@us.ibm.com",
      "firstname": "Murphy",
      "lastname": "Basore",
      "userstatus": "Active"
    }
  ]
}

i am getting below response in viewerData.

var viewerData = {
  "limit": 10,
  "start_offset": 0,
  "size": 2,
  "response": [
    {
      "userid": "harinissb@us.ibm.com",
      "firstname": "H",
      "userstatus": "Active"
    },
    {
      "userid": "tarnold@us.ibm.com",
      "firstname": "Twana",
      "userstatus": "Active"
    }   
  ]
};

Expected output

If i have AdminData then ‘name’: ‘Admin’, and need to prepare admin respnse. If i have ViewerData then ‘name’: ‘Viewer’, and need to prepare Viewer respnse.

export const rolesData = {
  'limit': 10,
  'start_offset': 0,
  'result': [
    {
      'name': 'Admin',
      'response': [
        {
            "userid": "mabasore@us.ibm.com",
            "firstname": "Murphy",
            "lastname": "Basore",
            "userstatus": "Active"
        }
      ]
    },
    {
      'name': 'Viewer',
      'response': [
        {
            "userid": "harinissb@us.ibm.com",
            "firstname": "H",
            "userstatus": "Active"
        }
      ]
    }
  ]
};

Advertisement

Answer

You can do it with combineLatest.

import { combineLatest } from 'rxjs';

getRolesData() {
  combineLatest([
    this.budgetaryUnitService.getUserList('Budget Administrator'),
    this.budgetaryUnitService.getUserList('Budget Viewer')
  ]).pipe(
    map(([adminData, viewerData]) => {
      const result = [];
      result.push(
        {
          name: 'Admin',
          response: adminData.response
        }
      );
      result.push(
        {
          name: 'Viewer',
          response: viewerData.response
        }
      );
      return {
        result
      };
    })
  ).subscribe( rolesData => {
    this.rolesData = rolesData;
  });
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement