我想将来自customers表的init数据加入到项目列表中。
模型是这样的:
项目
客户
你有一个例子,我如何使用angularfire2从angular2组件做到这一点?
我的控制器看起来像这样:
import { Component, OnInit } from '@angular/core';
import { Project } from '../project';
import { Router } from '@angular/router';
import { FirebaseAuth } from 'angularfire2';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { Observable } from 'rxjs';
@Component({
moduleId: module.id,
selector: 'app-projects',
templateUrl: 'projects.component.html',
styleUrls: ['projects.component.css']
})
export class ProjectsComponent implements OnInit {
projects: FirebaseListObservable<any[]>;
customers: FirebaseListObservable<any[]>;
projectName: string;
constructor(
private router: Router,
private af: AngularFire
) { };
ngOnInit() {
this.projects = this.af.database.list('projects');
}
add(projectName: string) {
this.af.database.list('projects')
.push({ name: projectName, id: '123' });
this.projectName = null;
}
}
更新
我已经从FirebaseListObservable将this.projects的类型更改为Observable 我的ngOnInit()方法现在看起来像这样:
ngOnInit() {
this.projects = this.af.database.list(`projects`)
.map(projects => {
projects.map(project => {
this.af.database.object('customer/' + project.customer + '/name')
.subscribe(customer => {
project.customer = customer;
})
return project;
})
return projects;
});
}
我现在可以从
中的模板访问客户的name属性<li *ngFor="let project of projects | async">
project.customer.$value
答案 0 :(得分:4)
不完全确定数据集的外观,所以我只想写一个基本的例子。假设一个像这样的结构:
- projects
- key
- name: string
- customers
- customerKey: boolean
- customers
- key
- name: string
示例数据
- projects
- projectId1
- name: "Cool project!",
- customers
- customerId1: true,
- customerId2: true
- projectId2
- name: "Another cool project!",
- customers
- customerId2: true,
- customerId3: true
- customers
- customerId1
- name: "John Smith"
- customerId2
- name: "John Doe"
- customerId3
- name: "John John"
因此,我们将客户的密钥存储在每个项目的customers
属性中。
假设我们要列出每个项目,但我们也希望获得客户的真实姓名,而不仅仅是他们的ID。由于firebase没有连接,我们必须手动执行此操作。这是一种方法:
this.projects = this.af.database.list(`projects`)
.map(projects => {
return projects.map(project => {
project.customers.map(customer => {
this.af.database.list(`customers`)
.subscribe(c => {
customer = c;
});
});
return project;
});
});
如果要异步获取数据(在这种情况下使用模板中的.subscribe
管道),内部.map
可以更改为简单async
。