问题
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