英文:
Cannot read properties of undefined (reading '<methodName>')
问题
我在 setTimeout()
中调用了一个方法,该方法又调用了 Angular 中的 HTTP 服务。
但是,当调用服务方法时,我收到以下错误消息:Cannot read properties of undefined (reading '<getUsernamesWithPattern>')
newFunc()
在 keyup
事件上被调用。
newFunc() {
clearTimeout(this.typingTimer);
if (this.myInput) //检查输入值是否有数据并且不为空
{
this.typingTimer = setTimeout(this.doneTyping, this.doneTypingInterval);
}
}
这个方法在 setTimeout
内部被调用:
doneTyping() {
//做一些事情
console.log("testing method" + this.myInput.value)
let pattern = this.myInput.value;
console.log(pattern);
this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
console.log(data);
});
}
我在这里缺少什么?由于 setTimeout
是一个异步函数,它应该能够调用服务,但它无法调用服务。
注意:我在构造函数中声明并初始化了 friendsListService
。
英文:
I have called a method in setTimeout()
which in turn calls an HTTP service in Angular.
But when the service method is being called I'm getting the following error: Cannot read properties of undefined (reading '<getUsernamesWithPattern>')
The newFunc()
is called on keyup
event.
newFunc() {
clearTimeout(this.typingTimer);
if (this.myInput) //checking if input value has some data and it's not empty
{
this.typingTimer = setTimeout(this.doneTyping, this.doneTypingInterval);
}
}
This method is being called inside of setTimeout
:
doneTyping() {
//do something
console.log("testing method" + this.myInput.value)
let pattern = this.myInput.value;
console.log(pattern);
this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
console.log(data);
});
}
What am I missing here? Since setTimeout
is an asynchronous function it should be able to call service but it's not able to call the service.
Note: I have declared initialized the friendsListService
in the constructor.
答案1
得分: 0
查看在setTimeout调用doneTyping方法时,this
关键字的情况。
this
的上下文发生了变化,它不再指向组件实例。
尝试:
newFunc() {
clearTimeout(this.typingTimer);
if (this.myInput) {
this.typingTimer = setTimeout(() => {
this.doneTyping();
}, this.doneTypingInterval);
}
}
doneTyping() {
console.log("testing method" + this.myInput.value);
let pattern = this.myInput.value;
console.log(pattern);
this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
console.log(data);
});
}
英文:
Look at this
keyword inside the doneTyping method when it is called by setTimeout.
The context of this
changes, and it no longer refers to the component instance.
Try:
newFunc() {
clearTimeout(this.typingTimer);
if (this.myInput) {
this.typingTimer = setTimeout(() => {
this.doneTyping();
}, this.doneTypingInterval);
}
}
doneTyping() {
console.log("testing method" + this.myInput.value);
let pattern = this.myInput.value;
console.log(pattern);
this.friendsListService.getUsernamesWithPattern(pattern).subscribe(data => {
console.log(data);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论