0

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 !

1 Answer 1

1

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
           };
        });
      )
    );
  }

 
Sign up to request clarification or add additional context in comments.

2 Comments

Does not working. Property 'results' does not exist on type 'ITestModel[]' There are only 2 properties id and url.
Ok, I updated the answer. Probably not the best solution, but hopefully it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.