【问题标题】:Reference to this is not accessible inside traditional function [duplicate]在传统功能中无法访问对此的引用[重复]
【发布时间】:2020-10-08 07:36:27
【问题描述】:

我正在使用 Angular 9 进行 Web 开发。我想在我的应用程序中实现 typeahead 功能。所以我正在使用 ng bootstrap typeahead。一切正常,如下面的代码所述。

search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(150),
      distinctUntilChanged(),
      switchMap(term =>
        this.GameService.getCode(term).pipe(
          catchError(() => {
            return of([]);
          }))
      ),
    )

但不知何故,这不适用于 IE 浏览器,因为它不支持箭头功能。为了解决这个问题,我用以下方式修改了代码:

search = function(text$: Observable<string>) {
    return text$.pipe(
      debounceTime(150),
      distinctUntilChanged(),
      switchMap(term => {
        let self = this;  // this is undefined and hence self is also undefined
        return self.GameService.getCode(term).pipe(
          map((res) => {
            this.isSearching = false;
            return res;
          }),
          catchError(() => {
            return of([]);
          }))
      }
      ),
    )
  }

如何自定义此代码以支持 IE 浏览器。

【问题讨论】:

  • 为什么不直接使用转译器?
  • 请注意,const self = this 需要位于function外部。此外,您的第二个 sn-p 仍在使用箭头函数,并且还有一个额外的 map() 调用,这在您的原始代码中不存在。
  • 能否请您详细说明一下

标签: javascript angular typescript bootstrap-typeahead


【解决方案1】:

在输入function 之前尝试定义let self = this

使用函数表达式时,您将失去代码的范围和对 this 的访问权限 - 因此您希望在输入第一个 function 之前保存您的 this

【讨论】:

  • 不适合我
  • 第二个代码 sn-p 中仍有一些箭头函数 - switchMap()map()catchError()
  • 尝试用传统的函数声明替换 switchMap 但仍然没有成功
  • 我不清楚你是替换了所有箭头函数还是只替换了 switchMap() 一个。
  • 我已经尝试替换所有箭头函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多