As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message:
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);
The code snippet I'm dealing with that's causing the confusion stems from following a tutorial:
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);
}
}
The HTTP request should ideally return an observable with the type of IEmployees interface that I've defined. However, it fails to work unless I amend my code like so public employees:any = []
. This workaround resolves the issue, but leaves me puzzled as to why it's necessary, especially since the tutorial runs without encountering this problem. Another concern arises when attempting to log the contents of the employees array after receiving data from the HTTP request within the ngOnInit()
method. Despite my efforts, the array appears empty (I even tried accessing properties like this.employees[0].name
). It leaves me wondering why I can't access the array within ngOnInit()
, yet have no trouble doing so in my HTML file using ngFor
to loop over and access object properties.
Here's the IEmployees interface for reference:
export interface IEmployee {
id: number,
name: string,
age : number
}