I am currently learning Angular through some tutorial and I came across a problem. I don't quite understand why is my console giving me error 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);
This is my code that I followed from 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);
}
}
Http request should return observable with type of IEmployees interface that i made, but it doesn't work unless I do this public employees:any = []
.This did solve my problem, but i don't understand why, since on tutorial it works without it. My second issue is when i try to Console log my employees array after i get my data with http request, to see what type of data it is, but it seems to be empty(i tried this.employees[0].name
also). Why cannot I access that array within ngOnInit()
but in my html file i can do it with ngFor
and access object properties. This is IEmployees interface
export interface IEmployee {
id: number,
name: string,
age : number
}
When declaring your employees array,
do this
public employees: IEmployee = [];
instead of this
public employees = []
;
This is because your service is retuning the data of type IEmployee
while the variable you're is using is not of that type
The this.employees[0]
is undefined
in ngOnInit
because the asynchronous request finishes later, than the ngOnInit
finishes. So the value of this.employees
will be assigned after the ngOnInit
is done. The ngFor
is also able to display the values of the property after the asynchronous response arrived.
You seem to be unsure whether you're going to receive a single Employee object or an array of Employees.
You have declared the getEmployees method in your Employee service to return an Observable<Employee>.
If your API returns an array of Employees, change the getEmployees method such that it returns an Observable<Employee[]>.
If your API returns a single Employee object, change the arrow function to the following: data => this.employees = [data].
To additionally log the output to the console, change the arrow function to: data => { console.log(data); // set this.employees;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.