无状态可观察服务中的错误:类型 'Observable<Course[]>' 不可分配给类型 'Observable<Course>'

Error in stateless observable service: Type 'Observable<Course[]>' is not assignable to type 'Observable<Course>'

我正在学习 rxjs,但遇到了这个错误。

我有以下方法

  getCourseById(id: number): Observable<Course> {
    return this.http.get<Course[]>('the-api').pipe(
      map(courses =>
          courses.filter(course => course.id === id)
        )
    )
  }

我调用特定的 API 端点,获取整个响应,然后使用 map 对该集合进行过滤,并获得 ID 等于参数 ID 的课程。

函数returns一个课程类型的 Observable。

然而,在控制台中我看到:

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     )
    ~~~~~

我不知道如何修复它。 我很感激帮助。 谢谢

您应该使用 Array.find() 而不是 Array.filter()。这只会 return 匹配对象:

getCourseById(id: number): Observable<Course> {
    return this.http.get<Course[]>('the-api').pipe(
      map(courses =>
          courses.find(course => course.id === id)!
        )
    )
}