0

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,
         });

       });
3
  • 1
    Just do it within subscribe callback Commented Jan 10, 2018 at 14:36
  • 2
    move the forEach inside the subscribe Commented Jan 10, 2018 at 14:39
  • just a comment apart for this, also use takewhile(falg) with subscribe and in onDestroy method set flag to false, otherwise your subscriber will be alive leading to memory leak in application. Commented Jan 10, 2018 at 18:17

3 Answers 3

2

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;
 });

}

Sign up to request clarification or add additional context in comments.

Comments

0

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,
                    });

                }),

        });
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.