Angular 16: Fetch APLI PLATFORM Hydra member, api in request

58 Views Asked by At

[enter image description here](https://i.stack.imgur.com/VL8Fx.png)

I want to create a table where following data is rendered. Id, sessionStart and SessionEnd is already fetched in the table and rendering correctly. I am not sure how to fetch the caliber, club, member and weaponCategory. The api calls on the backend side are written using 'API Platform'. It seems that those values are returning the url for the api to get the individual date. For example club: "/api/clubs/1'. That is the url to fetch the club. How should I write this in angular to get it rendered in the material table on the same time as the rest of the data?

This is the api call for the register list (result shown in screenshot)

API SERVICE:

getRegister() {
    return this.http.get<Register>(this.baseUrl + 'shooting_registers', this.httpOptions)
    .pipe(
      map((item: any) => {
        return item
      })
    )
  }

COMPONENT:

getRegister() {
    this.apiService.getRegister().subscribe((res: any) => {
      this.dataSource.data = res['hydra:member'];
      console.log('register lijst', res['hydra:member'])
    })
  }

RESULT API CALL:

{
"@context": "/api/contexts/ShootingRegister",
"@id": "/api/shooting_registers",
"@type": "hydra:Collection",
"hydra:totalItems": 1,
"hydra:member": [
    {
        "@id": "/api/shooting_registers/1",
        "@type": "ShootingRegister",
        "id": 1,
        "club": "/api/clubs/1",
        "member": "/api/members/139",
        "sessionStart": "2023-12-22T15:10:47+00:00",
        "sessionEnd": "2023-12-22T15:31:47+00:00",
        "caliber": "/api/calibers/1",
        "weaponCategory": "/api/weapon_categories/1"
    }
]

}

1

There are 1 best solutions below

0
Naren Murali On

From my understand, you need to club the APIs and fetch the data, then finally merge them into a single object!

Given the data in the question, this is an approximation of what you may need, please adjust it to suit your requirement!

genericGet(url: string) {
  return this.http.get<Register>(this.baseUrl + url, this.httpOptions);
}

getRegister() {
  return this.genericGet('shooting_registers')
    .pipe(
      switchMap((res: any) => {
        const data = res['hydra:member'];
        const apiData = data.map((item: any) => forkJoin({
          club: this.genericGet(item.club),
          member: this.genericGet(item.member),
          caliber: this.genericGet(item.caliber),
          weaponCategory: this.genericGet(item.weaponCategory),
          item: of(item),
        }).pipe(
          map(({ club, member, caliber, weaponCategory, item }) => {
            item.club = club;
            item.member = member;
            item.caliber = caliber;
            item.weaponCategory = weaponCategory;
            return item;
          })
        )
        );
        return forkJoin(apiData);
      })
    )
}