首页 > 解决方案 > 处理管道和订阅 firebase Query 对象的类似方法是什么?

问题描述

我在 Angular 中有一项服务,它使用以下从 Firebase 获取数据的方法:

getMatchesFiltered(matchId: string, filter: string, sortDirection: string, pageIndex: number, pageSize: number){
    return this.db.object('/matches');
  }

它返回一个我可以应用的firebase Observable pipesubscribe例如,

this.dbService.getMatchesFiltered(matchId, filter, sortDirection, pageIndex, pageSize).pipe(
                    catchError(()=> of([])),
                    finalize(()=>this.loadingMatches.next(false))
                  )
                  .subscribe(matches => {
                    let results = [];
                    let json_data = matches;
                    for(var i in json_data){
                      if(json_data[i].matchDeets){
                        results.push([i, json_data[i].matchDeets][1]);
                      }
                    }
                    this.matchesSubject.next(results);
                  });

但是,当我尝试从数据库服务返回查询时,返回的对象不再是 Observable:

getMatchesFiltered(matchId: string, filter: string, sortDirection: string, pageIndex: number, pageSize: number){
    let ref = firebase.database().ref("/matches");
    return ref.limitToFirst(pageSize);
  }

src/app/matchDataSource.model.ts(29,106) 中的错误:错误 TS2339:“查询”类型上不存在属性“管道”

关于如何以类似于 observable 的方式处理查询的文档似乎不是很及时。

例如,我可以在收到一个 DataSnapshot 之后做一些事情:

ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
  console.log(snapshot.key);
});

但这是否意味着我必须.on("child_added", function(snapshot) {});在我的组件中添加该部分,而不是将其很好地包装在服务中?

所以,我想我有以下问题:

  1. 我不知道如何正确划分/封装它。

  2. 如果我必须求助的话,我不知道如何处理管道命令对来自 component.ts 文件的查询所做的事情。

  3. 我不知道我是否遗漏了一些非常简单直接的方法来使查询的行为类似于 Observable。

如果需要,很高兴从 github 提供工作示例。

标签: javascriptangularfirebasefirebase-realtime-database

解决方案


Woudn;t 不可能把它放在一个 Observable 中:

Observable.create(function(observer) {
    ref.orderByKey().endAt("pterodactyl").on("child_added", snapshot => 
    {
        observer.next(snapshot.key);
    });
};

推荐阅读