Javascript NgZone在angular 4中未按预期工作
我延迟用户输入以匹配用户输入,当我使用Javascript NgZone在angular 4中未按预期工作,javascript,angular,zone,Javascript,Angular,Zone,我延迟用户输入以匹配用户输入,当我使用ngZone服务时,它会给我如下错误 core.es5.js:1084 ERROR TypeError: Cannot read property 'runOutsideAngular' of undefined at questions-box.component.ts:111 at ZoneDelegate.webpackJsonp.754.ZoneDelegate.invokeTask (zone.js:398) at Object.onInvokeT
ngZone
服务时,它会给我如下错误
core.es5.js:1084 ERROR TypeError: Cannot read property 'runOutsideAngular' of undefined
at questions-box.component.ts:111
at ZoneDelegate.webpackJsonp.754.ZoneDelegate.invokeTask (zone.js:398)
at Object.onInvokeTask (core.es5.js:4116)
at ZoneDelegate.webpackJsonp.754.ZoneDelegate.invokeTask (zone.js:397)
at Zone.webpackJsonp.754.Zone.runTask (zone.js:165)
at ZoneTask.invoke (zone.js:460)
at timer (zone.js:1540)
我已经在我的组件中正确导入并注入了ngZone服务
下面是我的代码片段
onCategoryChange() {
this.categorySearchTemp = null;
this._timeout = null;
if (this._timeout) {
window.clearTimeout(this._timeout);
}
this._timeout = window.setTimeout(function () {
this._timeout = null;
this.lc.runOutsideAngular(() => {
this.lc.run(() => {
console.log("VALUE", this.categorySearch);
this.getCategory(this.categorySearch);
});
});
}, 1000);
}
使用“fat arrow”功能保留“this”
应改为
window.setTimeout(()=> {...}), 1000)
下面是关于“fat arrow”的说明——“arrow函数表达式的语法比函数表达式短,并且不绑定自己的this、arguments、super或new.target。”
比如说,
class A {
callMeWithFatArrow() {
setTimeout( () => {
this.callThis();
});
}
callMe() {
setTimeout(function () {
try {
this.callThis();
}
catch (e) {
alert('exception' + e);
}
});
}
callThis() {
alert('i am here - callThis');
}
}
let a = new A();
a.callMe();
a.callMeWithFatArrow();
callMe-将发出异常警报,因为setTimeout使用一个常规函数来设置自己的异常
callMeWithFatArrow-将能够调用setTimeout中类A的另一个方法,因为在这种情况下setTimeout使用的“fat arrow”没有设置它自己的方法。您能否解释一下使用“fat arrow”函数保留“this”的更多信息,为什么要调用
区域lc
?
class A {
callMeWithFatArrow() {
setTimeout( () => {
this.callThis();
});
}
callMe() {
setTimeout(function () {
try {
this.callThis();
}
catch (e) {
alert('exception' + e);
}
});
}
callThis() {
alert('i am here - callThis');
}
}
let a = new A();
a.callMe();
a.callMeWithFatArrow();