Manik
Manik

Reputation: 11

how to push list of object value into array in angular4

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

Answers (3)

Uriel Chami
Uriel Chami

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

Sandip Jaiswal
Sandip Jaiswal

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

Sachila Ranawaka
Sachila Ranawaka

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

Related Questions