Angular 9:使用命名函数作为then(),listen()和subscribe()的参数的作用域范围

问题描述 投票:0回答:1

难以理解为什么我遇到范围问题。

当使用在then()内部定义的函数时,一切正常:

import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then((response: GoogleAuth) => {
          this.googleAuth = response;
      });
    });
  }
}

但是,当我尝试使用命名函数作为then()的参数时,出现错误(代码行旁边):

import GoogleAuth = gapi.auth2.GoogleAuth;
import GoogleUser = gapi.auth2.GoogleUser;

@Injectable()
export class MyService {
  constructor() { }

  private googleAuth: GoogleAuth = undefined;
  private clientConfig = { ... };

  private onInit(response: GoogleAuth): void {
    console.log(this); // undefined
    this.googleAuth = response; // Cannot read property 'googleAuth' of undefined
  }

  public init(): void {
    gapi.load('auth2', () => {
      gapi.auth2.init(this.clientConfig)
        .then(this.onInit);
    });
  }
}

我起初以为是因为我将undefined分配为“ googleAuth”的值,但是即使我运行“ console.log(this);”也是如此。在“ onInit”内部,undefined是控制台中显示的内容。如果我要手动调用该方法并传递期望的参数,则可以很方便地看到“ this”和“ this.googleAuth”。使用listen()和subscription()时,我有完全相同的问题。

我一直在尝试寻找答案,进行实验等,但是没有运气。请帮忙。谢谢!

angularjs angular scoping
1个回答
1
投票

您将函数this.onInit传递给then的方式,您失去了上下文。正确的方法是

    public init(): void {
      gapi.load('auth2', () => {
        gapi.auth2.init(this.clientConfig)
          .then((resp) => this.onInit(resp));
        });
    }

注意使用粗箭头功能。

© www.soinside.com 2019 - 2024. All rights reserved.