2016-10-02 81 views
7

我想在开始时加载所有的项目而不显示任何消息,但是在加载之后。我想捕获订阅者中的任何新行并将其显示给桌面通知。如何检查订阅是否完成加载所有现有的行?

问题是,我不确定如何检查是否加载了所有以前的项目,以及该行是新项目还是来自之前的现有项目。

this.items = this.af.database.list('notifications/'+this.uid+'/'); 
this.items.subscribe(list => { 
    list.forEach(row => { 
     // doing something here... 
    }); 

    // once all the rows are finished loading, then any new row, show desktop notification message 
}); 
+0

AngularFire2在内部执行此操作,并从observable发出当前'行'的数组。你将不得不自己检查数组,以确定什么是新的。相反,您可以使用底层的Firebase API。如果您使用'on(“child_added”,...)'和'once(“value”,...)',您在'value'事件之前收到的'child_added'事件将代表最初的'行',随后的'child_added'事件将包含新的'行'。 – cartant

+0

你有这样的例子与angularfire代码?我无法找到有关如何使用文档(“child_added”...) – Basit

+0

它位于底层的[Firebase API](https://firebase.google.com/docs/reference/js/firebase.database。参考)。你可以在列表中看到它在[AngularFire2源代码](https://github.com/angular/angularfire2/blob/2.0.0-beta.5/src/database/firebase_list_factory.ts#L102-L156)中的使用方式观察到的。 – cartant

回答

0

我对最少的代码用户lodash

// this varible holds the initial loaded keys 
let loadedKeys = []; 
this.items = this.af.database.list('notifications/'+this.uid+'/'); 
this.items.subscribe((list)=>{ 
    // we skip it while initial load 
    if(!_.isEmpty(loadedKeys)){ 
    // different is the new keys 
    let newKeys = _.difference(_.map(list, "$key"), loadedKeys); 
    if(!_.isEmpty(newKeys)){ 
     // ... notification code here 
    } 
    } 
    loadedKeys = _.map(list, "$key"); 
}); 
0

你正在寻找的的行为是RxJSdefault Subject方法。 检查this reactiveX url以遵循Publish Subject(相当于SubjectRxJS)的大理石图。

所以,你有两个简单的选择:

1)要显示like @bash replied

2手动指数女巫行)创建Rx.Subject()并且只分配了最新的行吧。然后你在你的应用程序工作流程中订阅这个主题。

方法2的优点是当发生新的.subscribe时,它不会检索以前的数据。


编辑:我写了this codepen为指导,以实现自定义RxJS Subject。希望能帮助到你。

相关问题