我将observable分配给我的列表时出现以下错误:
我可能会错过一个我无法弄清楚的技巧。如果有人可以对此有所了解,那就太棒了。这是我的app-data文件:
import * as _ from 'lodash';
import {Lesson} from "../shared/model/lesson";
import {Subject, Observable, Observer} from 'rxjs';
class DataStore {
private lessons : Lesson[] = [];
private lessonsListSubject = new Subject();
public lessonsList$: Observable<Lesson[]> = this.lessonsListSubject.asObservable();
initializeLessonsList(newList: Lesson[]) {
this.lessons = _.cloneDeep(newList);
this.broadcast();
}
addLesson(newLesson: Lesson) {
this.lessons.push(_.cloneDeep(newLesson));
this.broadcast();
}
deleteLesson(deleted:Lesson) {
_.remove(this.lessons,
lesson => lesson.id === deleted.id );
this.broadcast();
}
toggleLessonViewed(toggled:Lesson) {
const lesson = _.find(this.lessons, lesson => lesson.id === toggled.id);
lesson.completed = ! lesson.completed;
this.broadcast();
}
broadcast() {
this.lessonsListSubject.next(_.cloneDeep(this.lessons));
}
}
export const store = new DataStore();
答案 0 :(得分:4)
您需要声明lessonsListSubject
的类型,如下所示:
private lessonsListSubject: Subject<Lesson[]> = new Subject();
// or
private lessonsListSubject = new Subject<Lesson[]>();
答案 1 :(得分:0)
您可以从asObservable
投射返回值:
public lessonsList$: Observable<Lesson[]> =
this.lessonsListSubject.asObservable() as Observable<Lesson[]>;
这样,打字稿会将Observable<{}>
类型转换为Observable<Lesson[]>