如您所见,我正试图通过*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();
}发布于 2021-03-24 11:39:38
备选方案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>选项2: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>发布于 2021-03-24 11:50:04
您可以在使用JSON.parse(JSON.stringify(data))之前使用this.employee = data.map((e:any) =>{ // here I'm storing res in empty array
https://stackoverflow.com/questions/66780084
复制相似问题