【发布时间】:2021-08-30 02:54:54
【问题描述】:
由于某种原因,我无法在可观察对象 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.
但是每当我从pipe() 中的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() 时,它可以正常工作。我正在观看一个使用与此相同的代码但运行没有任何问题的教程,这与我的不同。
【问题讨论】:
标签: angular rxjs rxjs-observables rxjs-pipeable-operators