app.component.html 如您所见,我正在尝试通过 *ngFor
显示我的 firebase 项目的响应数据<div class="row">
<div class="col-md-3">
<h4 class="text-warning">All Employee Data</h4>
<div class="card" *ngFor="let item of employee">
<div class="card-body">
<div class="card-title">
Name: {{item.name}} // error-Property 'name' does not exist on type 'never'.
</div>
<div class="card-subtitle">
Age: {{item.age}} // error-Property 'name' does not exist on type 'never'.
</div>
<div class="card-text">
Address: {{item.address}} // same error here also
</div>
</div>
</div>
</div>
</div>
app.component.ts 如您所见,我正在尝试从 firesbase 项目中获取数据。
export class AppComponent implements OnInit {
title = 'App';
constructor( private _crudService:CrudService) {}
employee:[] = [];
employeeName: string = '';
employeeAge: number | undefined;
employeeAddress: string = '';
message: string ='';
ngOnInit(){
this._crudService.getAllEmployee().subscribe((data:any) =>{
this.employee = data.map((e:any) =>{ // here I'm storing res in empty array
return{
id: e.payload.doc.id,
name: e.payload.doc.data()['name'],
age: e.payload.doc.data()['age'],
address: e.payload.doc.data()['address']
}
});
console.log(this.employee);
});
}
crud.service.ts 如您所见,我正在发送获取员工数据的请求
getAllEmployee(){
return this.fireservice.collection('Employee').snapshotChanges();
}
答案 0 :(得分:1)
最初渲染组件时,数组 employee
为空。您可以使用安全导航运算符 ?.
在尝试呈现属性之前检查它是否可用。
<div class="card-title">
Name: {{ item?.name }}
</div>
<div class="card-subtitle">
Age: {{ item?.age }}
</div>
<div class="card-text">
Address: {{ item?.address }}
</div>
async
管道如果变量 this.employee
仅用于在模板中呈现输出,您可以跳过控制器中的订阅并在模板中使用 async
管道。
控制器
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
export class AppComponent implements OnInit {
title = 'App';
employees$: Observable<Array<any>>; // <-- type observable here
employeeName: string = '';
employeeAge: number | undefined;
employeeAddress: string = '';
message: string = '';
constructor(private _crudService: CrudService) {}
ngOnInit() {
this.employees$ = this._crudService.getAllEmployee().pipe(
map((e: any) => ({
id: e.payload.doc.id,
name: e.payload.doc.data()['name'],
age: e.payload.doc.data()['age'],
address: e.payload.doc.data()['address']
})),
tap(console.log) // <-- check the value
);
}
}
模板
<ng-container *ngIf="(employees$ | async) as employees">
<div class="row">
<div class="col-md-3">
<h4 class="text-warning">All Employee Data</h4>
<div class="card" *ngFor="let item of employees">
<div class="card-body">
<div class="card-title">
Name: {{ item['name'] }} <!-- bracket notation instead of dot notation -->
</div>
<div class="card-subtitle">
Age: {{ item['age'] }}
</div>
<div class="card-text">
Address: {{ item['address'] }}
</div>
</div>
</div>
</div>
</div>
</ng-container>
答案 1 :(得分:0)
您可以在之前使用 JSON.parse(JSON.stringify(data))
this.employee = data.map((e:any) =>{ // here I'm storing res in empty array