我是Angular和typescript的新手。相关代码如下:
export class SearchBarComponent {
constructor() { }
public timeDelay = 9999;
onSubmit(event){
console.log(this.timeDelay);
}
}我期望:
typed 9999相反,我得到了:
typed undefined我的第一个猜测是,这可能与timeDelay是私有的有关,但将其设置为公共并没有什么不同。正如你在下面看到的,我很容易找到一种解决办法,然而,我仍然对这种奇怪的行为感到好奇。
值得注意的一件事是,如果我在方法中定义类变量,它本身(this.timeDelay = 9999)就会在我下次访问它时记住它,因此在将TypeScript类变量编译成JS的过程中肯定有一些我不理解的地方。
这是完整的代码转储,以防我遗漏了其他内容:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-search-bar',
templateUrl: './search-bar.component.html',
styleUrls: ['./search-bar.component.scss'],
})
export class SearchBarComponent implements OnInit {
constructor() { }
ngOnInit() {
let searchbar = document.querySelector('ion-searchbar');
searchbar.addEventListener('ionInput', this.onSubmit);
}
//Used by onSubmit() method to record last input time
lastInputTime = null;
public timeDelay = 9999;
//called on every user input
//detects whether the user has stopped typing for an arbitrary amount of time and calls search method
onSubmit(event){
console.log("typed " + this.timeDelay);
//technically it's being defined here because defining it outside doesn't appear to work
this.lastInputTime = Date.now();
// ToDo import from settings file
// In milliseconds
const timeDelay = 1000;
setTimeout(
() => {
console.log(timeDelay + " " + (Date.now() - this.lastInputTime) + " " + this.lastInputTime);
//Detect if there was any keystroke in the last timeDelay
//-10 is a buffer
if (Date.now() - this.lastInputTime >= timeDelay - 10) {
console.log("submit: " + event.target.value.toLowerCase());
}
},
timeDelay
);
}
}发布于 2020-01-20 18:51:18
您的onSubmit变量正在不同的上下文中执行。因此,在onSubmit方法中,this与类的其余部分具有不同的值。
您需要将this上下文绑定到您的方法,如下所示:
searchbar.addEventListener('ionInput', this.onSubmit.bind(this));看看this Stackblitz演示。
编辑:对于将来遇到这种情况的任何人,正确的解决方案是使用<ion-searchbar (ionInput)="onSubmit($event)"></ion-searchbar>直接绑定组件。
https://stackoverflow.com/questions/59821602
复制相似问题