2017-05-06 124 views
0

enter image description here打字稿/角:找不到名称“XXX”

我有同样的打字稿组件两种功能。当我尝试调用已声明的一个时,VSCode报告它“[ts]找不到名称'XXX'。”。


按照要求通过Tiep Phan,这是全码:

liveSearchFMs(input: any) { 
    this._ectmService.getFMsFromUserSearch(input).subscribe(
    fanmissions => this.fanmissions = fanmissions, 
    error => this.errorMessage = <any>error 
); 
} 

timeout(input) { 
    var enteredValue = input; 
    var timeout = null; 
    clearTimeout(timeout); 
    timeout = setTimeout(function() { 
    this.liveSearchFMs(enteredValue); 
    }, 1000); 
} 
+0

显示你的代码而不提示 –

+1

使用箭头功能或者存储上下文我的回答下面将解决您的问题 –

+0

我一直看到这一点,这让没有意义:'error => this.errorMessage = 错误'。为什么类型断言?即使他错了,人们是否会模仿沃德贝尔? –

回答

1

我想你想创建这样的

export class EctmListComponent implements OnInit { 
    // other code 
    private timeoutTracker; 

    timeout(input) { 
     if (this.timeoutTracker) { 
      clearTimeout(this.timeoutTracker); 
     } 
     //use arrow function instead 
     this.timeoutTracker = setTimeout(() => { 
      this.liveSearchFMs(input); 
     }, 1000); 
     // or store context first 
     /* 
     const ctx = this; 
     this.timeoutTracker = setTimeout(function() { 
      ctx.liveSearchFMs(input); 
     }, 1000); 
     */ 
     // or using bind method 
     /* 
     this.timeoutTracker = setTimeout((function() { 
      this.liveSearchFMs(input); 
     }).bind(this), 1000); 
     */ 
    } 
} 
+0

伟大的解决方案Tiep。谢谢。有用。但只有一件事:你必须通过'clearTimeout(this.timeoutTracker)''改变'clearTimeout(timeoutTracker);''。 – Jonathan

+0

很棒:)....... –

0

您需要使用这个关键字。所以this.liveSearchFMs

+0

这是行不通的。我将它添加到相应的功能。 VSCode接受它,但是当我通过(keyup)事件调用** timeout($ event)**时,浏览器报告_this.liveSearchFMs不是function_。参考。 https://image.ibb.co/cgibQk/thisxxxnotafunction.png – Jonathan