Javascript 组件变量更改不持久
我在Angular 2(V4.0.1)中的组件中有以下代码,该组件具有输入,并通过(输入)属性响应更改:Javascript 组件变量更改不持久,javascript,angular,typescript,Javascript,Angular,Typescript,我在Angular 2(V4.0.1)中的组件中有以下代码,该组件具有输入,并通过(输入)属性响应更改: export class SearchDropdownComponent extends DropdownBaseComponent { @Output() Search: EventEmitter<any> = new EventEmitter(); InputValue: string = ''; SearchValue: string = null; S
export class SearchDropdownComponent extends DropdownBaseComponent {
@Output() Search: EventEmitter<any> = new EventEmitter();
InputValue: string = '';
SearchValue: string = null;
SearchTimer = 0;
SearchInputChange(Value: string) {
console.log('+SearchInputChange')
// If the Search output is not assinged to anything, do nothing
// if (this.Search.observers.length > 0) // This comparison doesn't work??
// return;
// console.log('has Search observers');
// Update the InputValue on every change
this.InputValue = Value;
console.log('this.SearchValue is: ' + this.SearchValue);
// If already searching, don't do anything else
if (this.SearchValue != null)
return;
console.log('not searching yet');
// Clear any existing timer, since the value has changed before the timer expired
if (this.SearchTimer !== 0)
window.clearTimeout(this.SearchTimer);
// Start a new timer with the current value
this.StartTimer(Value);
}
SearchTimeout(Value) {
console.log('setting this.SearchValue to: ' + Value);
this.SearchValue = Value;
this.Search.emit({SearchFor: Value, Callback: this.SearchDone});
}
SearchDone() {
console.log('+SearchDone');
// Value changed while search was in progress
if (this.InputValue !== this.SearchValue) {
console.log('Value changed during search');
let Value = this.SearchValue;
this.StartTimer(Value);
}
console.log('resetting this.SearchValue');
// No longer searching
this.SearchValue = null;
}
StartTimer(Value) {
console.log('starting timer..');
this.SearchTimer = window.setTimeout(() => {
this.SearchTimeout(Value);
}, 400);
}
}
请注意“resetting this.SearchValue”这一行,它将值重置为null。几秒钟后,一些字符被输入到编辑中,导致再次调用SeearchInputChange,但this.SearchValue恢复到原来的状态
编辑2:
后来我发现(我应该意识到),问题在于线路:
this.Search.emit({SearchFor: Value, Callback: this.SearchDone});
调用回调时,它不是同一个实例。将其更改为:
this.Search.emit({SearchFor: Value, SearchDropdown: this});
..在视图组件中调用SearchDropdown.SearchDone()可以解决此问题。这并不完全理想,所以我想知道是否有一种更“被接受”的方式来做到这一点 我怀疑您的
StartTimer(Value)
函数是原因,因为它在延迟一段时间后调用了SearchTimeout
。将console.log放入setTimeout()
中并检查序列。它应该在超时后调用SearchTimeout,因此得名。注意发射器是如何在该函数中激发的。响应发射器的组件调用回调(即SearchDone),该回调将重置SearchValue。之后,下次键入任何内容时,SearchValue应该为null,但在这种情况下,它不是。您可以在窗口中放置控制台。log
。setTimeout
并记录value
的值并进行检查吗?
this.Search.emit({SearchFor: Value, SearchDropdown: this});