Reputation: 11
employeeView() method will get the list of employee data as an object,i want to store each object data into array
constructor(private userService: employeeviewservices) {
this.userService.employeeView().subscribe(data => this.EmployeeData=data),
this.EmployeeData.forEach(i=>{
this.resultArray.push(
{
"id":i.id,
"name":i.name,
});
});
Upvotes: 0
Views: 699
Reputation: 418
Both answers below are the same and are right. The proper way to solve your issue is to do the push of the array inside the suscribe.
Nontheless I feel the need to explain why.
The suscription to the event "userService.employeeView()" is asyncronic. Which means that it will wait until the request ends to run the suscription method (which populates your array).
In your code you are saying "whenever employeeView ends, do this (populate my array)" and right after that "please tell me, what do we have in this array?" and it will be none. Beacause the array is not populated yet.
Upvotes: 0
Reputation: 3730
Use following code:
constructor(private userService: employeeviewservices) {
let newData: any= [];
this.userService.employeeView().subscribe((data: any[]) => {
newData = data.map(d: any => {
return {
"id":d.id,
"name":d.name,
};
});
this.resultArray = newData;
});
}
Upvotes: 2
Reputation: 41445
Do it inside the subscribe.
constructor(private userService: employeeviewservices) {
this.userService.employeeView().subscribe(data => {
this.EmployeeData = data;
this.EmployeeData.forEach(i => {
this.resultArray.push({
"id": i.id,
"name": i.name,
});
}),
});
}
Upvotes: 0