RxJs:类型 'unknown[]' 不可分配给类型 'Course[]'



由于某些原因,我无法在可观察的courses$中的pipe()运算符中使用shareReplay()

以下是home.component.ts

import {Component, OnInit} from '@angular/core';
import {Course} from "../model/course";
import { Observable } from 'rxjs';
import {interval, noop, of, timer} from 'rxjs';
import {catchError, delayWhen, map, retryWhen, shareReplay, tap} from 'rxjs/operators';
import { createHttpObservable } from '../common/util';

@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
beginnerCourses$: Observable<Course[]>;
advancedCourses$: Observable<Course[]>;

constructor() {
}
ngOnInit() {
const http$ = createHttpObservable('/api/courses');
const courses$: Observable<Course[]> = http$
.pipe(
tap(() => console.log('HTTP request')), // tap() operator is used to produce the side effects in our obsevable chain. Whenever we want to update something outside of our observable chain, we use the tap() operator.
map(res => Object.values(res['payload'])),
shareReplay()
); // Whenever we want to derive new observables from existing observables, we need to use one of the RxJs operators, the pipe() operator. The pipe() function is what allows us to chain multiple operators in order to produce a new observable.
this.beginnerCourses$ = courses$
.pipe(
map(courses => courses.filter(course => course.category == 'BEGINNER'))
)
this.advancedCourses$ = courses$
.pipe(
map(courses => courses.filter(course => course.category == 'ADVANCED'))
)

当我尝试运行它时,我得到了这个错误:

Error: src/app/home/home.component.ts:30:15 - error TS2322: Type 'Observable<unknown[]>' is not assignable to type 'Observable<Course[]>'.
Type 'unknown[]' is not assignable to type 'Course[]'.
Type '{}' is missing the following properties from type 'Course': id, description, iconUrl, courseListIcon, and 3 more.

但每当我从courses$中的pipe()中删除shareReplay()时,它都会起作用。这里可能有什么问题?我希望能够在没有任何错误的情况下使用shareReplay()

home.component.html

.courses-panel {
max-width: 400px;
margin: 0 auto;
}
<div class="courses-panel">
<h3>All Courses</h3>
<mat-tab-group>
<mat-tab label="Beginners">
<courses-card-list [courses]="beginnerCourses$ | async">
<!--What "async" pipe does is, it's going to subscribe to this observable "beginnerCourses$" and it's going to retrieve that data and assign it to the "[courses]".-->
</courses-card-list>
</mat-tab>
<mat-tab label="Advanced">
<courses-card-list [courses]="advancedCourses$ | async"></courses-card-list>
</mat-tab>
</mat-tab-group>

</div>

以上是HTML和CSS供参考。当我删除shareReplay()时,它工作起来没有任何问题。我正在看一个教程,它使用了与此相同的代码,但运行起来没有任何问题,与我的不同。

所以,事实证明,我所要做的就是像这样使用shareReplay()

shareReplay<Course[]> 

现在,它开始工作了!

最新更新