【问题标题】:Listening firebase changes from components with angular监听具有角度的组件的 Firebase 变化
【发布时间】:2018-06-01 14:28:23
【问题描述】:

我想访问多个组件中的一些数据。我创建了一个服务,为此目的检索数据。当我尝试观察我的数据时出现问题。我的代码:

@Injectable()
export class NotificationsService {

    constructor(private af: AngularFireDatabase) {}

    public retrieveNotifications(): Observable<NotificationObj[]> {
      return this.af.database.ref(refs.NOTIFICATIONS).on('value', snap => {
        const data = snap.val();
        return Object.keys(data).map(key => {
          return new NotificationObj(key, data[key]);
        });
      })
    }
}

我收到消息:

TS2322:类型 '(a: DataSnapshot, b?: string) => any' 不可分配给  'Observable' 类型。类型中缺少属性“_isScalar”(a:DataSnapshot,b?:string)=>any'。

如何转换我的方法以避免在服务之外解析数据并节省监听组件更改的可能性?

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

    我在那里找到了解决方案Firebase error when subscribing to ref.on(‘value’, callback); | Property 'subscribe' does not exist on type '(a: DataSnapshot, b?: string) => any'

    完整的代码是:

      public retrieveNotifications(): Observable<NotificationObj[]> {
        return Observable.create(subscriber => {
          const ref = this.af.database.ref(refs.NOTIFICATIONS);
          const callback = ref.on('value', snap => {
            const data = snap.val();
            const notifications = Object.keys(data).map(key => {
              return new NotificationObj(key, data[key]);
            });
            subscriber.next(notifications);
          });
          return () => ref.off('value', callback);
        })
      }
    

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多