2

Following is my code :

        var me = this;
        gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) {
            if (authResult && !authResult.error) {
                me.accessToken = authResult.access_token;

            } else {

              //TODO : show error in front end
            }
        });

when i use callback function like this.

gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, AuthResult);

function AuthResult(authResult: any) {
                if (authResult && !authResult.error) {
                    me.accessToken = authResult.access_token;

                } else {

                  //TODO : show error in front end
                }

I dont get the me property in that callback function

How i can wrap the callback function in other callback function where i can get the scope also in JS

Shan Khan
  • 9,667
  • 17
  • 61
  • 111

2 Answers2

1

Use a fat arrow:

    gapi.auth.authorize({ client_id: client, scope: scope, immediate: true },AuthResult);

    const AuthResult = (authResult: any) => {
            if (authResult && !authResult.error) {
                this.accessToken = authResult.access_token;

            } else {
              //TODO : show error in front end
            }

More

Don't use .bind : https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html at least not yet

basarat
  • 261,912
  • 58
  • 460
  • 511
  • if i have to use the same work in javascript instead of typescript. Bind would be fine then or harmful as described in link too/ – Shan Khan Mar 30 '16 at 23:10
0

Use .bind:

gapi.auth.authorize(..., AuthResult.bind(this));

function AuthResult(...) {
  // use `this` instead of `me`
}

See also How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143