Querying subset from angularfire2

最后都变了- 提交于 2019-12-11 07:28:37

问题


I need to get a subset from a firebase list. Let's say I have two sets:

set1 = {
    dog:true,
    cat:true,
    snake:true,
    bull:true
}

and

set2 = {
    dog:true,
    cat:true
}

What I need is to get the "in set1, but not in set2", in this case it would return:

setresult = {
    snake:true,
    bull:true
}

I tried to achieve this with map:

this.setresult = this.af.database.list('/set2/').map((animals) => {
        return animals.map((animal) => {
            if (auth.uid == _user.$key || af.database.object('set2/' + animal.$key) == null) {}
            else {

                return af.database.object('set1/' + animal.$key);
            }
        })
    })

But I end up with a list with nulls, and I need only the result set.

Thanks in advance.


回答1:


You can use the combineLatest operator to compose an observable that emits an object containing the keys/values from set1 that are not in set2:

import * as Rx from "rxjs/Rx";

let set = Rx.Observable.combineLatest(

    // Combine the latest values from set1 and set2
    // using AngularFire2 object observables.

    this.af.database.object('/set1/'),
    this.af.database.object('/set2/'),

    // Use the operator's project function to emit an
    // object containing the required values.

    (set1, set2) => {
        let result = {};
        Object.keys(set1).forEach((key) => {
            if (!set2[key]) {
                result[key] = set1[key];
            }
        });
        return result;
    }
);

set.subscribe((set) => { console.log(set); });


来源:https://stackoverflow.com/questions/39624799/querying-subset-from-angularfire2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!