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?
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"]
.