Why I get TypeError: undefined is not an object (evaluating '') in 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
returns id 数组,我用 console.log
打印了 returns 有效数字。
但是list-centers.component.ts
中的方法在控制台打印错误,并没有调用center.service.ts
中的另一个方法。
错误:
TypeError: undefined is not an object (evaluating 'this.centers')
centers: Center[];
中心数组的数据:
通过使用 foreach(function...,您将失去 this 作用域。您可以尝试使用 lambda foreach(p => {...
这是因为 typecrypt 保证 lambda 中的作用域但不起作用的方式。您也可以使用函数和闭包
我有自定义服务 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
returns id 数组,我用 console.log
打印了 returns 有效数字。
但是list-centers.component.ts
中的方法在控制台打印错误,并没有调用center.service.ts
中的另一个方法。
错误:
TypeError: undefined is not an object (evaluating 'this.centers')
centers: Center[];
中心数组的数据:
通过使用 foreach(function...,您将失去 this 作用域。您可以尝试使用 lambda foreach(p => {...
这是因为 typecrypt 保证 lambda 中的作用域但不起作用的方式。您也可以使用函数和闭包