首页 文章

订阅ref.on时出现Firebase错误('value',回调); |属性'subscribe'在类型'(a: DataSnapshot, b?: string) => any'上不存在

提问于
浏览
6

我在角度使用firebase实时数据库 . 我试图从firebase服务器实时获取一些数据:(来自服务的代码)

getData(child){
        return firebase.database().ref(child).on('value', (snapshot) => {
            console.log(snapshot.val())
        })
    }

并订阅我的组件中的上述功能:

this.examinerService.getData('batches/names').subscribe(
      (batches) => {
        this.batches = batches.val();
      }
    )

这给了我错误:

Property 'subscribe' does not exist on type '(a: DataSnapshot, b?: string) => any'

我已经尝试使用 ref().once() 工作正常,但我想要实时行为 .

更新:目前我在我的组件中使用 database().ref().on('value', (snapshots) => { console.log(snapshots.val()); }); 工作正常但我想在我的服务中进行并在我的组件中订阅它 . 有人告诉我,它不是一个可观察的,所以你可以知道如何制作一个可观察的并用它绑定快照 .

3 回答

  • 7

    函数 getData 正在返回传递的回调而不是 Observable ,这正是代码所期待的 . 你可以修改这个函数,以便返回 .subscribe() ,你可以 .subscribe() .

    import { Observable } from 'rxjs/Observable';
    
    getData(child) {
    
      return Observable.create(subscriber => {
        const ref = firebase.database().ref(child);
    
        const callbackFn = ref.on('value',
          // emit a value from the Observable when firebase data changes
          (snapshot) => subscriber.next(snapshot.val()),
    
          // error out the Observable if there is an error
          // such as permission denied
          error => subscriber.error(error)
        );
    
        // The function passed to Observable.create can return a callback function
        // which will be called when the observable we created is unsubscribed from.
        // Just as we used `ref.on()` previously our callback function calls `ref.off`
        // to tell firebase that we are no longer interested in the changes
        return () => ref.off('value', callbackFn);
      });
    }
    
  • 1

    假设我们的数据结构看起来像这样

    {
      batches: {
        names: [
          {
            first: 'FirstName',
            last: 'LastName'
          },
          {
            first: 'FirstName1',
            last: 'LastName1'
          }
        ]
      }
    }
    

    对于名称,我们可能有一个看起来像这样的界面

    export interface Name { first: string; last: string; }
    

    然后我们有一个看起来像这样的服务

    import { Injectable } from '@angular/core';
    import { Name } from "./name";
    import { AngularFireDatabase, AngularFireList } from "angularfire2";
    
    
    @Injectable()
    export class NameService {
    
      constructor(private db:AngularFireDatabase) { }
    
      getAllNames(): AngularFireList<Name> {
          return this.db.list('batch/name');
      }
    
    }
    

    最后我们的组件看起来像这样

    import { Component, OnInit } from '@angular/core'
    import { AngularFireList } from "angularfire2";
    
    @Component({
      selector: 'app-name-list',
      template: `
      <div *ngFor="let name of names$">
        {{ name.last }}, {{ name.first }}
      </div>
    `
    })
    
    export class NameListComponent implements OnInit {
      names$: AngularFireList<Name>;
    
      constructor(private nameService: NameService) {}
    
      ngOnInit() {
        this.names$ = nameService.getAllNames();
      }
    }
    

    Angular使用websockets实时更新 . 我不确定,但我认为这可能是你正在寻找的行为 .

  • -2

    .subscribe() 不会工作,因为返回类型不是 Observable . 你在回调函数中获得 DataSnapshot . 尝试

    getData(child){
        return firebase.database().ref(child);
    }
    

    并在您的组件中

    this.examinerService.getData('batches/names').on('value', (snapshot) => {
            console.log(snapshot.val())
        })
    

相关问题