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

Posted

技术标签:

【中文标题】如何解决无法读取属性错误?【英文标题】: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)

【问题讨论】:

【参考方案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。但只有在刷新网页时,我才能看到更新后的列表。

以上是关于如何解决无法读取属性错误?的主要内容,如果未能解决你的问题,请参考以下文章

如何解决“未捕获的类型错误:无法读取未定义的属性'get'”? (Vue.JS 2)

如何解决未捕获的类型错误:无法读取未定义的属性“调用”?

我该如何解决这个问题:未捕获的类型错误:无法读取 javascript 中未定义的属性“toString”

如何解决 TypeError:无法读取未定义的属性“过滤器”

如何解决:无法读取节点 js 中未定义的属性“keycloak-token”?

如何解决此MarkerCluster签入/签出错误(传单salesforce)?