【发布时间】:2018-11-19 18:36:24
【问题描述】:
此时我正在使用 Rxjs 中的 Subject 没有任何问题,简单示例:
服务
rooms: Room[] = [];
roomsSubject = new Subject<Room[]>();
emitRooms() {
this.roomsSubject.next(this.rooms);
}
getRooms() {
firebase.database().ref('/rooms').on('value', data => {
this.rooms = data.val() ? Object.values(data.val()) : [];
console.log(data.val());
this.emitRooms();
}, error => {
console.log("getRooms: ", error);
});
}
组件:
rooms: Room[];
roomsSubscription: Subscription;
ngOnInit() {
this.roomService.getRooms();
this.roomsSubscription = this.roomService.roomsSubject.subscribe((rooms: Room[]) => {
this.rooms = rooms;
});
}
一切正常,但在这种情况下,我只需要一个 Observable(我不从客户端发出数据)。所以我尝试将此代码更新为:
getRooms() {
return firebase.database().ref('/rooms').on('value', data => {
return of(data.val());
}, error => {
console.log("getRooms: ", error);
});
}
组件:
ngOnInit() {
this.roomsSubscription = this.roomService.getRooms().subscribe((rooms: Room[]) => {
this.rooms = rooms;
});
}
订阅时出错:
error TS2339: Property 'subscribe' does not exist on type '(a: DataSnapshot, b?: string) => any'
更新后:
getRooms(): Observable<any> {
我明白了:
error TS2322: Type '(a: DataSnapshot, b?: string) => any' is not
assignable to type 'Observable<any>'. Property '_isScalar' is
missing in type '(a: DataSnapshot, b?: string) => any'.
我一直在使用 stackoverflows 来纠正我的错误,并且一直遇到新的错误。我正在使用 Visual Studio Code 进行开发。
是否有机会在没有 Angularfire 的情况下使用 Observable?
【问题讨论】:
标签: angular firebase firebase-realtime-database rxjs observable