Issue
Having some trouble understanding why I'm having scoping issues.
When using functions defined inside of then()
, everything works fine:
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;
});
});
}
}
But, when I try to use a named function as argument for then(), I get an error (next to line in code):
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);
});
}
}
I thought at first it was because I assigned undefined as the value for "googleAuth", but even if I run "console.log(this);" inside of "onInit", undefined is what appears in the console. If I were to call the method manually and pass the expected parameters, it has no trouble seeing "this" and "this.googleAuth". I have the exact same issues when using listen() and subscribe().
How can I fix this issue?
Solution
The way you passed in the function this.onInit
to then
, you looses the context. Proper way to do it is
public init(): void {
gapi.load('auth2', () => {
gapi.auth2.init(this.clientConfig)
.then((resp) => this.onInit(resp));
});
}
Note the use of fat arrow function.
Answered By - printfmyname
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.