【问题标题】:Type 'Observable<(T | R[])[]>' is not assignable to type 'Observable<[T, R[]]>类型 'Observable<(T | R[])[]>' 不可分配给类型 'Observable<[T, R[]]>
【发布时间】:2019-01-31 15:09:35
【问题描述】:

我正在尝试将数据从两个 observable 映射到第三个,例如

  return this.coursesService
  .findCourseByUrl(route.params['id'])
  .pipe(
    switchMap((course: Course) =>
      this.coursesService
        .findLessonsForCourse(course.id)
        .pipe(map((lessons: Lesson[])=> [course, lessons)])
    )
  );

但我得到以下异常

Type 'Observable<(Course | Lesson[])[]>' is not assignable to type 'Observable<[Course, Lesson[]]>'.
Type '(Course | Lesson[])[]' is not assignable to type '[Course, Lesson[]]'.
Property '0' is missing in type '(Course | Lesson[])[]'.

我发现 switchMap 中的 resultSelector 在 rxJs6 中已被弃用,这就是我尝试这种方法的原因。但是卡在了这里。

【问题讨论】:

    标签: rxjs6 switchmap


    【解决方案1】:

    想出了以下两种方法,但不确定第二种解决方案。

    第一个解决方案:在映射最终的 observable 时显式添加类型。

    return this.coursesService
      .findCourseByUrl(route.params['id'])
      .pipe(
        switchMap((course: Course) =>
          this.coursesService
            .findLessonsForCourse(course.id)
            .pipe(map(lessons => [course, lessons] as [Course, Lesson[]])),
        ),
      );
    

    第二个解决方案

    return this.coursesService
      .findCourseByUrl(route.params['id'])
      .pipe(
        switchMap((course: Course) =>
          this.coursesService
            .findLessonsForCourse(course.id)
            .pipe(merge(lessons => [course, lessons])),
        ),
      );
    

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 1970-01-01
      • 2018-03-09
      • 2018-08-14
      • 2021-01-02
      • 2020-11-23
      • 2019-01-12
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多