[英]Why I get TypeError: undefined is not an object (evaluating '') in Angular?
I have custom service service.center.ts
which contains the following delete method: 我有自定义服务
service.center.ts
,其中包含以下删除方法:
deleteCenter(id: number): Observable<{}> {
console.log(id);
const url = `${this.D_ROOT_URL}${id}`;
return this.http.delete(url);
}
I have the button in the template: 我在模板中有按钮:
<button type="submit" (click)="deleteCenter()">Delete</button>
which calls the following method in list-centers.component.ts
: 在
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();
});
}
}
The this.getCheckedCenters
returns the array of ids, and I printed with console.log
which returns valid number. this.getCheckedCenters
返回ID数组,我打印了console.log
并返回有效数字。
But the method in list-centers.component.ts
print error in console, and doesn't call another method in the center.service.ts
. 但是
list-centers.component.ts
的方法在控制台中显示错误,并且不会在center.service.ts
调用另一个方法。
Error: 错误:
TypeError: undefined is not an object (evaluating 'this.centers')
TypeError:未定义不是对象(评估“ this.centers”)
centers: Center[];
By using foreach(function..., you are losing the this scope. You can try using a lambda foreach(p => {... 通过使用foreach(function ...,您将失去此作用域。您可以尝试使用lambda foreach(p => {...
This is because of the way typescrypt guarantees scopes in lambdas but not function. 这是因为typecrypt保证了lambda中的作用域而不是功能。 You could alternatively use function and a closure
您也可以使用函数和闭包
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.