【问题标题】:How do I solve a Cannot read property error?如何解决无法读取属性错误?
【发布时间】:2018-08-03 03:29:26
【问题描述】:

以下是在控制台中引发错误的代码块。该功能是在我的 Angular 应用程序的服务中实现的。

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

这是错误:

错误类型错误:无法读取未定义的属性“id” EmployeesService.lastEmployeeID (employees.service.ts:43) 在 AddEmployeeFormComponent.onSubmit (addemployee-form.component.ts:19) 在 Object.eval [as handleEvent] (AddEmployeeFormComponent.html:3) 在 handleEvent (core.js:13542) 在 callWithDebugContext (core.js:15051) 在 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)

【问题讨论】:

    标签: node.js angular express observable


    【解决方案1】:

    我将尝试在这里解释问题:

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

    【讨论】:

    • 进行此更改会影响我不应该发生的其他功能。我似乎无法弄清楚原因。
    • 是的,该函数现在返回一个可观察对象而不是一个值。您需要从调用它的任何位置订阅此函数的结果。
    • 好的,谢谢。但现在我正在做一个更新后端服务器 json 对象的 http.post。但只有在刷新网页时,我才能看到更新后的列表。
    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多