假设数据看起来像这样
post: {
authorId: '123AA',
title: 'first Post',
body: 'yay'
}
author: {
uid: '123AA',
displayName: 'Richard'
email: 'im@richard.com'
}
我想使用作者姓名发布帖子:
<div className="post">
<div className="title">{post.title}</div>
<div className="body">{post.body}</div>
<div className="author-name">{post.author.displayName}</div> //problem
</div>
提取的帖子项目仅包含作者uid
,但我需要作者的displayName
。检索帖子时如何填充作者字段?这就是我现在要取的帖子:
const postsRef = firebase.database().ref('posts/')
postsRef.on('value', (snapshot) => {
this.setState({posts: snapshot.val()})
})
答案 0 :(得分:8)
在真实的firebase中不确定,但我经常在angular2中使用join。这是我的示例代码。
import { Component, OnInit } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'app',
templateUrl: `
<ul>
<li *ngFor="let p of posts | async">
{{ p.title }} - {{ (p.authorName | async)?.displayName }}
</li>
</ul>
`
})
export class InitComponent implements OnInit {
posts: Observable<any[]>;
constructor(private af: AngularFire) {}
ngOnInit() {
this.posts = this.af.database.list('/posts')
.map(posts => {
posts.map(p => {
p.authorName = this.af.database.object('/authors/'+p.authorId);
});
return posts;
});
}
数据库结构如下:
/posts/postId/{authorId, title, body}
/authors/authorId/{displayName, email}
希望这有帮助