AngularFire2: Retrieve Double Nested Object by Property Value

孤街浪徒 提交于 2019-12-12 04:01:45

问题


I'm not sure why, but I'm having a hard time with this. Consider the following model:

threads
    threadId
        posts
            postId
                author: authorId

This structure made sense for me, as I wanted to render the posts in the thread view within ngFor. Now I want to display lists of posts written by specific users in their profile view. But I'm having a hard time figuring out how to get them into an observable list.

Since there are multiple keys in the path to the object I want, I have to do a lot of mapping to get there. But it seems like lists within the list referred to by the Firebase ref path aren't iterable. So, for example:

getPosts(uid: string): Observable<any> {
    let results = this.af.database.list(`/threadsMeta`)
    .do(threads => {
        threads.forEach(thread => {
            let posts = thread.posts
            posts.forEach(post => {
                // Not even sure what I'd do here,
                // but posts isn't iterable, so it's moot
            })
        })
    })
    return results
}

This makes sense since it's an object, not an array. How about this?

getPosts(uid: string): Observable<any> {
    let results = this.af.database.list(`/threadsMeta`)
    .do(threads => {
        threads.forEach(thread => {
            return this.af.database.list(`threadsMeta/${thread.$key}/posts`)
            .map(posts => posts.filter(post => post.author === uid))
        })
    })
    results.subscribe(data => console.log(data))
    return results
}

Nope. This doesn't filter anything.

I need a list of posts whose author properties are equal to the uid param.

Update:

Right now I'm doing this, and it works, but it feels awfully ugly.

getPosts(uid: string): Observable<any> {
    let posts: any[] = []
    return this.af.database.list(`/threadsMeta`)
    .map(threads => {
        threads.forEach(thread => {
            for (var post in thread.posts) {
                if (thread.posts[post].author === uid) {
                    posts.push(thread)
                }
            }
        })
    return Observable.of(posts)
    })
}

回答1:


try this :

getPosts(uid: string): Observable<any> {
    return this.af.database.list(`/threadsMeta`)
    .map(threads => {
        let posts = [];
        threads.forEach(thread => {
            posts = thread
                      .posts
                      .filter(post => {
                         posts => posts.filter(post => post.author === uid)
                      })
        });
        return posts;
    })
}

you call it like this:

getPosts("123").sucbscribe(posts=>{
   ///posts
});


来源:https://stackoverflow.com/questions/43077939/angularfire2-retrieve-double-nested-object-by-property-value

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