0

I have a function that subscribes to a search api. In the map function I would like to map the items to objects. I do not get an error but the response is always empty.

this is my code:

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.forEach(item => {
      new SearchResult(
          item.id,
          item.title,
          item.price
      );
  }) || []);
1
  • what's with the || [] at the end there? Commented May 4, 2017 at 13:54

2 Answers 2

4

You need to change forEach with map and return from it:

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.map(item => {
    return new SearchResult(
      item.id,
      item.title,
      item.price
    );
  }))
  .catch((err: Response) => { 
    // handle error
  })

forEach doesn't return anything, while map produces new array with items which you return from callback.

Also, note that || [] check is useless. If json.items is an array then map will always produce another array. If it's not an array then it will throw error, which you need to handle with .catch block attached after your .map (Obeservable map I mean).

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

2 Comments

thank you very much, but toskv was a littel bit faster
@TobiasEtter Haha, actually I was 1 minute faster, but whatever ;)
2

You need to map over the returned list and transform it instead of forEach.

Also, if the list of items is empty map will return an empty list, you don't need to do the || [] anymore.

return this.http.get(searchURL)
  .map((res: Response) => res.json())
  .map(json => json.items.map(item => {
    return new SearchResult(
      item.id,
      item.title,
      item.price
    );
  }));

Comments

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.