[Fixed] Angular // Http Request // Export class array with objects

Issue

I need to Fetch data from a JSON API. Looking documentation the first thing I’ve to do it’s to write the export class. My problem is that I cannot understand how to manage an array of objects.

This is my JSON API:

[
{
    "id": 312,
    "name": "Other Managerial Limits",
    "riskMeasureAreas": [
        {
            "id": 4,
            "name": "MARKET RISK",
            "riskControlCategoryId": 312
        },
        {
            "id": 6,
            "name": "Counterparty Risk",
            "riskControlCategoryId": 312
        }
    ]
},

And that’s my app.component.ts

import { Component } from '@angular/core';

export class RiskControlCategory {
  constructor(
    public id: number,
    public name: string,
    public riskMeasuresAreas: object[], <----??? I'm blocked here 
  ) {
  }
}

Any help? Thank you in advance

Solution

The question isn’t clear at the moment. If all you wish to do is to create a type conforming to the response of the API, you could use Typescript Interface to define the models.

Eg. response.ts

export interface Response {   // <-- `Response` is an example. Name it according to your requirement
  id: number;
  name: string;
  riskMeasureAreas: RiskMeasureArea[];
}

export interface RiskMeasureArea {
  id: number;
  name: string;
  riskControlCategoryId: number;
}

You could then import and use it where it’s required

Service

import { Response } from './response';

export class DataService {
  getData(): Observable<Response[]> {       // <-- type here
    return this.http.get(url).pipe(
      map((res: any) => <Response[]>(res))  // <-- mapping the type
    );
  }
}

Component

import { Response } from './response';

export class SomeComponent implements OnInit {
  response: Response[];

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData().subscribe({
      next: (res: Response[]) => {
        this.response = res;
        // do something else with the response
      },
      error: (error) => {
        // handle error
      }
    });
  }
}

Leave a Reply

(*) Required, Your email will not be published