我有一些问题我无法在角度5中显示来自Firebase的$ key值 我得到所有其他值,但$ key我无法显示它
以下是我的服务代码
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs';
import { Employee } from '../Employee';
@Injectable()
export class EmployeeService {
employees: AngularFireList<any[]>;
Employee: AngularFireObject<any>;
constructor(
public af: AngularFireDatabase
) {
this.employees = this.af.list('/employees/employees') as AngularFireList <Employee[]>;
}
getEmployees(): AngularFireList <any> {
return this.employees ;
}
}
这是我的组件
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../../services/employee.service';
import { Employee } from '../../Employee';
import { all } from 'q';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
employees : Employee [][];
constructor(public employeeService : EmployeeService ) {
}
ngOnInit() {
this.employeeService.getEmployees().valueChanges().subscribe( employees => {
this.employees = [employees[0]] ;
console.log(this.employees);
})
}
}
这是所有变量的接口
export interface Employee{
$key?:string;
firstName?:string;
lastName?:string;
email?:string;
country?:string;
city?:string;
phone?:number;
salary?:number;
}
最后是用于显示数据的html代码
<tr *ngFor="let item of employees">
<th >{{item.firstName}}</th>
<th >{{item.lastName}}</th>
<th >{{item.email}}</th>
<th >{{item.country}}</th>
<th >{{item.city}}</th>
<th >{{item.phone}}</th>
<th >{{item.salary}}</th>
<th >{{item.$key}}</th>
</tr>
键的引用
答案 0 :(得分:0)
我在这里找到了解决方案。 https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md
组件中的代码变为
ngOnInit() {
this.employeeService.getEmployees().snapshotChanges().map(actions => {
return actions.map(action => ({ key: action.key, ...action.payload.val() }));
}).subscribe( employees => {
this.employees = [employees[0]];
console.log(this.employees);
})
}
答案 1 :(得分:0)
在component.ts中尝试这种方式。 /请注意,我选择了snapshotChanges()。 然后只有你可以访问键值。
items:Observable<any>;
constructor(private db:AngularFireDatabase){
this.items = db.list('person').snapshotChanges() ;
然后通过HTML我们可以访问键值
*ngFor="let item of items | async ">
Item key value is : {{item.key}}