AngularFire2:按属性值检索双嵌套对象

时间:2017-03-28 19:07:44

标签: angular firebase angularfire2

我不确定为什么,但我很难用这个。考虑以下模型:

threads
    threadId
        posts
            postId
                author: authorId

这个结构对我来说很有意义,因为我想在ngFor内的线程视图中呈现帖子。现在,我想显示特定用户在其个人资料视图中撰写的帖子列表。但是我很难弄清楚如何将它们放入可观察的列表中。

由于在我想要的对象的路径中有多个键,我必须做很多映射才能到达那里。但似乎Firebase ref路径引用的列表中的列表不可迭代。所以,例如:

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
}

这是有道理的,因为它是一个对象,而不是一个数组。怎么样?

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
}

不。这不会过滤任何内容。

我需要一个author属性等于uid参数的帖子列表。

更新

现在我正在这样做,但是它有效,但感觉非常难看。

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 个答案:

答案 0 :(得分:0)

试试这个:

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;
    })
}

你这样称呼它:

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