假设数据看起来像这样
- 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()})
- })
解决方法
在真正的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}
希望这可以帮助