如何解决无法读取属性错误?

时间:2018-02-23 05:28:31

标签: node.js angular express observable

以下是在控制台中抛出错误的代码块。该功能在我的角度应用程序的服务中实现。

    lastEmployeeID()  //code block that's throwing error
    {
     let temp= this._http.get(this._employeesUrl).subscribe((employees:any) 
      =>  temp = employees,err => console.log(err));
     let last=temp[temp.length-1].id;
     return last;
    }    

这是错误:

  

错误TypeError:无法读取未定义的属性“id”   EmployeesService.lastEmployeeID(employees.service.ts:43)at   AddEmployeeFormComponent.onSubmit(addemployee-form.component.ts:19)   在Object.eval [as handleEvent](AddEmployeeFormComponent.html:3)at   handleEvent(core.js:13542)在callWithDebugContext(core.js:15051)at at   Object.debugHandleEvent [as handleEvent](core.js:14638)at   dispatchEvent(core.js:9957)at eval(core.js:12296)at   SafeSubscriber.schedulerFn [as _next](core.js:4339)at   SafeSubscriber .__ tryOrUnsub(Subscriber.js:240)

1 个答案:

答案 0 :(得分:0)

我会尝试解释这里的问题:

lastEmployeeID() {
  // Here you're assigning the subscription to the get request to temp
  let temp= this._http.get(this._employeesUrl).subscribe(
    (employees:any) =>  temp = employees, // This will only happen when the get request completes
    err => console.log(err)
  );

  // By the time you get here, the get request will most likely not 
  // have finished and so "temp = employees" will not have been called. 
  // So you are trying to get temp[temp.length-1] where temp is not an 
  // array but rather a subscription.
  let last=temp[temp.length-1].id;
    return last;
  }    

以下是一种可以解决此问题的方法:

lastEmployeeID(): Observable<any> {
  return new Observable(observer => {
    this._http.get(this._employeesUrl).subscribe(employees => {
      observer.next(employees[employees.length-1].id)
    }, err => {
      console.log(err))
      observer.error(err)
    }
  })
}