难以理解为什么我遇到范围问题。
当使用在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()时,我有完全相同的问题。
我一直在尝试寻找答案,进行实验等,但是没有运气。请帮忙。谢谢!
您将函数this.onInit
传递给then
的方式,您失去了上下文。正确的方法是
public init(): void {
gapi.load('auth2', () => {
gapi.auth2.init(this.clientConfig)
.then((resp) => this.onInit(resp));
});
}
注意使用粗箭头功能。