2017-04-23 70 views
1

餘米延遲用戶輸入來匹配用戶的打字,當我使用ngZone服務,它給我的錯誤一樣NgZone未按預期角4

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); 

} 
+0

爲什麼叫'zone''lc'? – HankCa

回答

1

使用「胖箭頭」功能來保存「這個」

window.setTimeout(function() {...}), 1000) 

應改爲

window.setTimeout(()=> {...}), 1000) 

以下是MDN說,關於「胖箭頭」 - 「箭頭函數表達式不是函數表達式更短的語法和不綁定自己的這一點,爭論,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(); 

呼我 - 會提醒例外,因爲setTimeout的使用常規的功能,設置自己的這個

callMeWithFatArrow - 將能夠裏面調用A類的另一種方法setTimeout的原因是setTimeout在這種情況下使用「胖箭頭」,它並沒有設置它自己的這個。

+0

你能解釋一點關於使用「胖箭頭」功能來保存「this 「 –