我在 Angular 中有一个服务,使用以下方法从 Firebase 获取数据:
getMatchesFiltered(matchId: string, filter: string, sortDirection: string, pageIndex: number, pageSize: number){
return this.db.object('/matches');
}
它返回一个 firebase Observable,我可以对其应用 pipe
和 subscribe
,例如,
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);
});
但是,当我尝试从数据库服务返回一个 Query 时,返回的对象不再是一个 Observable:
getMatchesFiltered(matchId: string, filter: string, sortDirection: string, pageIndex: number, pageSize: number){
let ref = firebase.database().ref("/matches");
return ref.limitToFirst(pageSize);
}
ERROR in src/app/matchDataSource.model.ts(29,106): error TS2339: Property 'pipe' does not exist on type 'Query'
关于如何以类似于 observable 的方式处理查询的文档似乎不是很及时。
例如,我可以在收到 DataSnapshot 后做一些事情:
ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
console.log(snapshot.key);
});
但这是否意味着我必须在我的组件中添加 .on("child_added", function(snapshot) {});
部分,而不是将其很好地包装在服务中?
所以,我想我有以下问题:
我不知道如何正确地划分/封装它。
如果我必须求助于 component.ts 文件,我不知道如何处理管道命令正在执行的操作。
我不知道我是否遗漏了一些非常简单直接的方法来使查询的行为类似于 Observable。
如果需要,很乐意提供来自 github 的工作示例。
最佳答案
是否可以将其放入 Observable 中:
Observable.create(function(observer) {
ref.orderByKey().endAt("pterodactyl").on("child_added", snapshot =>
{
observer.next(snapshot.key);
});
};
关于javascript - 处理管道和订阅 firebase Query 对象的类似方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50770409/