【问题标题】:Speech recognition callback this is not defined inside call back语音识别回调 this 未在回调中定义
【发布时间】:2019-01-24 06:50:12
【问题描述】:

我正在尝试使用语音识别实例,并且在成功回调中我正在尝试使用语音术语来调用 api。问题是成功回调“this”被视为语音识别对象的实例,而不是类实例。

接下来,我浏览了一些解决方案并将 this 实例复制到 that 变量中并调用了函数。现在函数调用正在工作,但所有角度绑定都失败了。代码sn-p如下:

 voiceSearch() {
    console.log('listening');

    if ("webkitSpeechRecognition" in window) {
      const vSearch = new webkitSpeechRecognition();
      vSearch.continuous = false;
      vSearch.interimresults = false;
      vSearch.lang = 'en-US';
      vSearch.start();
      let that = this;

      vSearch.onresult = function (e) {
        voiceHanlder.value = e.results[0][0].transcript;
        that.searchTerm = voiceHanlder.value;
        vSearch.stop();
        that.searchProducts(that.searchTerm); // unable to use this code without using that = this

      }

      vSearch.onerror = function (e) {
        console.log(e);
        vSearch.stop();
      }
    }
    else {
      console.log('Your browser does not support speech recognition');
    }
  }

     searchProducts(searchTerm: string) {
        this.searchMade = true;
        this.getProducts(searchTerm).subscribe(resp => {
          this.searchedProducts = resp['records'];
          this.searchValue = "Now showing the searched products";
          console.log(this.searchedProducts);
        })
      }

我把代码改成:

  vSearch.onresult ( (e) => {
    voiceHanlder.value = e.results[0][0].transcript;
    that.searchTerm = voiceHanlder.value;
    vSearch.stop();
    that.searchMade = true;
    that.searchCvsProducts(that.searchTerm);
    that.listeningOn = false;
    //voiceSearchForm.submit();
  })

但我收到一个错误,例如 vSearch.onResult is not a function。

我们可以使用粗箭头运算符来避免 that = this 代码吗?

【问题讨论】:

  • 应该是vSearch.onresult = (e) => { ... }。
  • @connorsFan - 我已经能够使用胖箭头以及 function.prototype.bind 但现在我看到一个问题,即 angular 在立即回调后没有更新它的绑定。然而,在我进行另一次搜索后,它也在做同样的事情。任何想法都一样。我可以手动触发绑定操作,但这并不能解释为什么它们不应该首先工作。如果我不做语音识别,那绝对没问题。
  • 尝试按照this answer 中的建议将代码封装在NgZone.run(() => { ... }) 中。

标签: angular typescript this


【解决方案1】:

您需要使用 na 箭头函数来捕获 this 上下文。

vSearch.onresult = (e) => {
        voiceHanlder.value = e.results[0][0].transcript;
        this.searchTerm = voiceHanlder.value;
        vSearch.stop();
        this.searchProducts(this.searchTerm);
}

我建议您阅读TypeScript Handbook 中的函数章节,它很好地解释了this 如何在函数中工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2016-08-09
    相关资源
    最近更新 更多