【问题标题】:Firebase good use of Observable (rxjs) on angular 2+Firebase 在 Angular 2+ 上很好地使用 Observable (rxjs)
【发布时间】: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


    【解决方案1】:

    错误的原因是您正在返回从firebase.database().ref('/rooms').on(...) 返回的任何内容,这是一个(a: DataSnapshot, b?: string) =&gt; any 类型的值。你想发送的是Observable

    为此,在这种情况下,您可以简单地使用 Observable.create。如果出现错误,您可以使用throwError:

    ...
    import { Observable, throwError } from 'rxjs';
    ...
    
    @Injectable()
    export class RoomService {
    
      getRooms(): Observable<any> {
        return Observable.create(observer => {
          firebase.database().ref('/rooms').on('value', data => {
            return observer.next(data.val());
          }, error => {
            return throwError(error);
          });
        });
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2019-01-16
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多