繁体   English   中英

为什么会出现TypeError:undefined不是Angular中的对象(求值”)?

[英]Why I get TypeError: undefined is not an object (evaluating '') in Angular?

我有自定义服务service.center.ts ,其中包含以下删除方法:

deleteCenter(id: number): Observable<{}> {
  console.log(id);
  const url = `${this.D_ROOT_URL}${id}`;
  return this.http.delete(url);
}

我在模板中有按钮:

<button type="submit" (click)="deleteCenter()">Delete</button>

list-centers.component.ts调用以下方法:

deleteCenter(): void {
  if (this.getCheckedCenters.length > 0) {
    this.getCheckedCenters.forEach(function (id) {
      id = +id;
      this.centers = this.centers.filter(c => c.id !== id);
      this.centerService.deleteCenter(id).subscribe();
    });
  }
}

this.getCheckedCenters返回ID数组,我打印了console.log并返回有效数字。

但是list-centers.component.ts的方法在控制台中显示错误,并且不会在center.service.ts调用另一个方法。

错误:

TypeError:未定义不是对象(评估“ this.centers”)

centers: Center[];

中心数组的数据: 在此处输入图片说明

通过使用foreach(function ...,您将失去此作用域。您可以尝试使用lambda foreach(p => {...

这是因为typecrypt保证了lambda中的作用域而不是功能。 您也可以使用函数和闭包

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM