我正在使用Angular 8应用程序。我正在使用可观察模式形式rxjs。但是我仍然在Observable线上遇到错误。
Google当然会报错。但是没有找到正确的答案。
所以我导入了这个:
import { Subject, Observer, Observable } from 'rxjs';
我有这行:
public lessonList$: Observable<Lesson[]> = this.lessonListSubject.asObservable();
但是我仍然收到此错误:
Type 'Observable<unknown>' is not assignable to type 'Observable<Lesson[]>'.
Type '{}' is missing the following properties from type 'Lesson[]': length, pop, push, concat, and 26 more.ts(2322)
该错误将消失。
谢谢
oke,这是界面Lesson:
export interface Lesson {
id: number;
description: string;
duration?: string;
completed?: boolean;
}
这是整个文件:
import * as _ from 'lodash';
import { Lesson } from '../shared/model/lesson';
import { Subject, Observer, Observable } from 'rxjs';
class DataStore {
private lessons: Lesson[] = [];
private lessonListSubject = new Subject();
public lessonList$: Observable<Lesson[]> = this.lessonListSubject.asObservable();
initaliseLessonList(newList: Lesson[]) {
this.lessons = _.clone(newList);
this.broadCast();
}
addLesson(newLesson: Lesson) {
this.lessons.push(newLesson);
this.broadCast();
}
deleteLesson(deleted: Lesson) {
_.remove(this.lessons, lesson => lesson.id === deleted.id);
this.broadCast();
}
toggleView(toggled: Lesson) {
// tslint:disable-next-line: no-shadowed-variable
const lesson = _.find(this.lessons, lesson => lesson.id === toggled.id);
lesson.completed = !lesson.completed;
this.broadCast();
}
broadCast() {
this.lessonListSubject.next(_.cloneDeep(this.lessons));
}
}
export const store = new DataStore();
答案 0 :(得分:5)
替换
private lessonListSubject = new Subject();
通过
private lessonListSubject = new Subject<Lesson[]>();
那样,您有一个Subject<Lesson[]>
而不是Subject<unknown>
。