I'm learning rxjs and I got stuck with this error.
I have the following method
getCourseById(id: number): Observable<Course> {
return this.http.get<Course[]>('the-api').pipe(
map(courses =>
courses.filter(course => course.id === id)
)
)
}
I make a call to a particular API endpoint, grab the entire response, then use map to filter against that collection and get the course with id equals to the parameter id.
The function returns an Observable of type Course.
Yet, in the console I see:
error TS2322: Type 'Observable<Course[]>' is not assignable to type 'Observable<Course>'.
Type 'Course[]' is missing the following properties from type 'Course': id, name, url, description
27 return this.http.get<Course[]>('the-api').pipe(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28 map(courses =>
~~~~~~~~~~~~~~~~~~~~~
...
30 )
~~~~~~~~~
31 )
~~~~~
I don't know how to fix it. I'd appreciate help. Thanks
CodePudding user response:
You should use Array.find()
instead of Array.filter()
. This will only return the matching object:
getCourseById(id: number): Observable<Course> {
return this.http.get<Course[]>('the-api').pipe(
map(courses =>
courses.find(course => course.id === id)!
)
)
}