Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct mapping to interface when getting data from a given URL

I am new to Angular and I am trying to map the returned json to my interface but failed.

Here's the link to the code I have.

  • Stackblitz
  • Json URL
like image 310
Jeju Avatar asked Dec 06 '25 05:12

Jeju


2 Answers

You dont need to use map since you response is object and as i see you want to map data property from that.

One way to do it would be

  getTestData(): Observable<TestObject>{
    const url = 'https://api.myjson.com/bins/11x4bx';

    // return this.http.get(url).pipe(
    //   map(response => ((response || {} as any).data || []).map(testData => this.mapTest(testData))));


    return this.http.get(url).pipe(
      map((resp: any) => {
          return <TestObject> {
            id: resp.data.id,
            view: resp.data.view,
            resourceName: resp.data.resourcename,
            loadCapacity: resp.data.loadcapacity
          }
      })
      );


  }

Cleaner way

  getTestData(): Observable<TestObject>{
    const url = 'https://api.myjson.com/bins/11x4bx';
    return this.http.get(url).pipe(pluck('data'));
  }
like image 78
Vova Bilyachat Avatar answered Dec 08 '25 20:12

Vova Bilyachat


When you are not sure about how to build an interface for your response, you can use JSON2TS

declare module namespace {

    export interface Meta {
        entityName: string;
    }

    export interface Data {
        id: string;
        view: string;
        startdate: string;
        enddate: string;
        erp: string;
        loadcapacity: string;
        userid: string;
        resourceid: string;
        resourcename: string;
        userdatalimitationid: string;
        requestleaveforself: boolean;
        bookforself: boolean;
        lastmodified: string;
    }

    export interface RootObject {
        meta: Meta;
        data: Data;
    }

}
like image 45
Sajeetharan Avatar answered Dec 08 '25 18:12

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!