我正在学习新的方法,以用angular 4创建应用程序,现在在我的文件之一中
export class AppComponent {
str: string = "";
arr = [];
constructor(private elemRef: ElementRef, private rend: Renderer, private objComp: AppObjComponent) {
}
@HostListener('keyup', ['$event']) textKeyPressed(ev) {
console.log(this.elemRef);
if (ev) {
this.str = ev.target.value;
console.log(this.str);
this.objComp.obj.forEach(function(elem, index) {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
})
}
在编译时,在浏览器上编译正常,会引发错误
AppComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'str' of undefined
这行是
if(elem.includes(this.str))
但是,如果我使用console.log打印,它将以相同的功能打印。
console.log(this.str);
我不确定为什么要对此this.str引发错误,如果我对此this.str行进行注释,它也会对this.arr引发错误。不知道为什么它不能访问类变量。
答案 0 :(得分:1)
forEach中的this
不是您班上的this
。
要保留课程的上下文,请使用粗箭头:
this.objComp.obj.forEach((elem, index) => {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
})
或使用forEach的thisArg
参数(请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)来告知:
如果为forEach()提供了thisArg参数,它将用作 回调的这个值。否则,未定义的值将用作 它的这个值。回调最终可观察到的this值是 根据通常的规则来确定 通过功能。
所以:
this.objComp.obj.forEach(function(elem, index) {
if (elem.includes(this.str)) {
this.arr.push(this.str);
}
}, this ) // this added here
答案 1 :(得分:0)
您需要在中使用每个箭头功能,或者将范围绑定到该功能(最好是第一个选项)