Search code examples
angulartypescriptrxjs-observables

Try to transform object (type casting) using map operator in angular


Api response (json) -

{
    "count": 1050,
    "next": "....",
    "previous": null,
    "results": [
        {
            "name": "Test1",
            "url": "https://test/1/"
        },
        {
            "name": "Test2",
            "url": "https://test/2/"
        }
     ]
}

Interface:

export interface ITestModel{
  name: string;
  url: string;
}

Service:

getData(): Observable<ITestModel[]> {
    return this.http.get<ITestModel[]>(this.apiUrl).pipe(
      map((res) =>
        res.map((data) => ({
          name: data.name,
          url: data.url
        }))
      )
    );
  }

Error: (When I subscribe the above function in controller)

core.js:4352 ERROR TypeError: res.map is not a function at MapSubscriber.project (test.service.ts:19)

Expectation:

  1. In getData() function, I would like to transform observable as ITestModel[]
  2. Expected output while subscribe (Json)

[ { "name": "Test1", "url": "https://test/1/" }, { "name": "Test2", "url": "https://test/2/" } ]

Thank you !


Solution

  • Try this:

    getData(): Observable<ITestModel[]> {
        return this.http.get<any>(this.apiUrl).pipe(
          map((res) =>
            res.results.map((data) => {
              return { 
                 name: data.name,
                 url: data.url
               };
            });
          )
        );
      }