-2

I followed a documentation, where they used:

findLessons():  Observable<Lesson[]> {
  return this.http.get('http://localhost:3000/api/lessons').pipe(
      map(res =>  res["payload"])
  );
}

However this didn't work, I got an undefined.

I came up with this solution, which works fine:

 findLessons(): Observable<Lesson[]> {
    return this.http.get<Lesson[]>('http://localhost:3000/api/lessons');
  }

So why did 1 not work? Are the solutions the same? Which solution is preferred?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ibrahim
  • 85
  • 8
  • Could you provide the route response ? According to your code, you don't have a `payload` property from the response. That's why you get `undefined` – Emilien Mar 29 '21 at 15:04
  • If the second example is correct, and the API returns an array of lesson objects, it's unclear what you expected the first example to do. It didn't work because the API doesn't return an object with a payload property, they're clearly not the same because you get different outcomes and the preferred solution is the one that's actually a solution, the one that works. – jonrsharpe Mar 29 '21 at 15:06
  • _"Which solution is preferred?"_ I always prefer the solution that returns the correct result. – Thomas Sablik Mar 29 '21 at 18:05

1 Answers1

1

In the 1st example, you're receiving an API response but you're only interested in returning the payload property. You got undefined, meaning the API response didn't include a payload property.

In the 2nd example, you're receiving an API response that you expect will deserialize to Lesson[] and you're going to return it.

It's not a matter of what solution is preferred, you're doing different things and apparently the 1st one didn't comply with your API response.

Talking about "preferred" things, the notation res.payload is preferred to res["payload"].

Isaac
  • 184
  • 9