在subscribe()方法Angular 2之外的变量是未定义的

时间:2018-02-22 05:34:21

标签: angularjs-scope angular2-services

我正在处理角度2并且在subscribe()函数之外的变量中得到未定义的错误。employee变量id undefinedsubscribe()函数之外。请帮助我。谢谢。以下是代码

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: "mohit@ommzi.com", emp_phone: "9800000", emp_status: "y"}
    })
  }
}

1 个答案:

答案 0 :(得分:1)

因为您正在使用Observable,所以在设置员工之前会调用console.log(this.employee)。我建议您在editEmployee中返回Promise并使用:

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

请注意,它不是最好和最美丽的解决方案,但是如果你想让代码保持这种风格,我就会这样做。