Ale*_*lex 11 javascript firebase-realtime-database angularfire2 angular
我想将来自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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新
我已经从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;
});
}
Run Code Online (Sandbox Code Playgroud)
我现在可以从里面的模板访问不是客户的名称属性
<li *ngFor="let project of projects | async">
project.customer.$value
Run Code Online (Sandbox Code Playgroud)
不太确定您的数据集是什么样子,所以我只写一个基本示例。假设结构如下:
- projects
- key
- name: string
- customers
- customerKey: boolean
- customers
- key
- name: string
Run Code Online (Sandbox Code Playgroud)
示例数据
- 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"
Run Code Online (Sandbox Code Playgroud)
因此,我们将客户的密钥存储在每个项目的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;
});
});
Run Code Online (Sandbox Code Playgroud)
如果您想异步获取数据,可以将内部.subscribe更改为简单的(在本例中使用模板中的管道)。.mapasync
| 归档时间: |
|
| 查看次数: |
2397 次 |
| 最近记录: |