Home > Enterprise >  Fetching object in object in Angular
Fetching object in object in Angular

Time:05-12

I'm trying to fetch data from my back-end API and I do not know how to fetch an object inside another one.

Here is the response of my back-end :

{
    "id": 4,
    "website_id": 1,
    "user_id": 5,
    "username": "Swarton3"
},
{
    "id": 5,
    "website_id": 1,
    "user_id": 5,
    "username": "Test123"
}

In the website_id property, i'd like to fetch data from another endpoint which return informations about that website.

So the final thing should be like this :

{
    "id": 4,
    "website": {
        "id": 2,
        "name": "Test2",
        "url": "test2.com"
    },
    "user_id": 5,
    "username": "Swarton3"
},
{
    "id": 5,
    "website": {
        "id": 1,
        "name": "Test",
        "url": "test.com"
    },
    "user_id": 5,
    "username": "Test123"
}

What is the best way to do that in a service ? Should fetch all the data in my back-end ?

CodePudding user response:

First of all my suggestion would be to reconsider your API. Because if you had many objects in your response you would end up having too many http requests.
Otherwise you can use combination of RxJS switchMap and forkJoin operators.

// assuming you have have two methods in your service
// yourService.fetchRecords to fetch the first level data,
// yourService.fetchWebsite to fetch the website by its website_id.
// then the method which return the full data would be like below:
fetchFullData(): YourData {
  this.yourService.fetchRecords().pipe(
    switchMap((records) => {
      const websiteRequests = records.map(record => this.yourService.fetchWebsite(record.website_id));
      return forkJoin(websiteRequests).pipe(
        map((websites) => records.map((record, idx) => ({
          id: record.id,
          user_id: record.user_id,
          username: record.username,
          website: websites[idx]
        })))
      );
    })
  )
}

Explanation: switchMap is used to map an outer observable to an inner one. In your case the outer observable is the one created by this.yourService.fetchRecords(). The inner observable is the one created by the forkJoin func. forkJoin accepts an array of observables and returns a single observable that emits only once all the accepted observable complete. So in case of observables created by yourService.fetchWebsite(), it will only emit when all the corresponding websites are fetched.

  • Related