【问题标题】:AngularFire2: Retrieve Double Nested Object by Property ValueAngularFire2:按属性值检索双重嵌套对象
【发布时间】:2017-03-28 19:07:44
【问题描述】:

我不知道为什么,但我很难接受。考虑以下模型:

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

【问题讨论】:

    标签: angular firebase angularfire2


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • thread.posts.filter 不是函数。我认为您不能以这种方式使用过滤器。
    猜你喜欢
    • 2021-05-09
    • 2017-09-27
    • 2021-09-27
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2023-04-06
    • 2020-11-03
    相关资源
    最近更新 更多