Search code examples
angularjs-scopeangular2-services

variable is undefined outside of subscribe() method Angular 2


I am working on angular 2 and getting undefined error for variable outside of subscribe() function.employee variable id undefined outside subscribe() function.Please help me.Thanks. Below is the code

export class DetailsComponent implements OnInit {
  employee;

  constructor(private _location:Location, private _empService:EmpService, private route:ActivatedRoute) { }
  ngOnInit() {
      //let params:any = this.route.snapshot.params;

      this.editEmployee(6); //I have tried to pass static value
      console.log(this.employee); //Here this is undefined  
  }
  backClicked() {
        this._location.back();
    }

   editEmployee(id) {
    this._empService.getEmployee(id).subscribe((employee)=> {
       this.employee = employee[0];
       console.log(employee[0]); //This have below output in console
       //{id: "6", emp_name: "Mohit", emp_email: "[email protected]", emp_phone: "9800000", emp_status: "y"}
    })
  }
}

Solution

  • Because you are using Observables, the console.log(this.employee) gets called before the employee is set. I would recommend in editEmployee that you return a Promise and use:

    editEmployee(id) {
        return new Promise((resolve) => {
            this._empService.getEmployee(id).subscribe((employee)=> {
                this.employee = employee[0];
                console.log(employee[0]);
                resolve();
            });
        });
    }
    
    this.editEmployee(6).then(()=> {
        console.log(this.employee);
    }
    

    Note that it's not the best and most beautiful solution, but if you want to keep your code in this style i would do it like this.