【发布时间】:2021-03-25 08:20:32
【问题描述】:
我目前正在通过一些教程学习 Angular,但遇到了一个问题。我不太明白为什么我的控制台给我错误
ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignable to type 'any[]'.17 .subscribe(data => this.employees = data);
这是我从教程中遵循的代码:
export class EmployeeDetailComponent implements OnInit {
public employees = [];
constructor(private _employeeService : EmployeeService) { }
ngOnInit(): void {
this._employeeService.getEmployees()
.subscribe(data => this.employees = data);
console.log(this.employees);
}
}
Http 请求应该返回我创建的 IEmployees 接口类型的 observable,但除非我这样做public employees:any = [],否则它不起作用。这确实解决了我的问题,但我不明白为什么,因为在教程中它有效没有它。我的第二个问题是,当我通过 http 请求获取数据后尝试控制台记录员工数组,以查看它是什么类型的数据,但它似乎是空的(我也尝试过 this.employees[0].name)。为什么我不能在ngOnInit() 中访问该数组,但在我的html 文件中我可以使用ngFor 来访问并访问对象属性。
这是 IEmployees 接口
export interface IEmployee {
id: number,
name: string,
age : number
}
【问题讨论】:
标签: javascript angular typescript