0

i have the folloing code:

export class AuthService {
  token: string;
  refreshToken: string;
  constructor(private router: Router) { }

  signinUser(username: string, password: string) {
      const user = new mylib.User(username, password);
      user.requestSessionToken(true, {
        onOk: function (result) {
          let tokenMap: any;
          tokenMap = result;
          this.token = tokenMap.sessionToken;
          this.refreshToken = tokenMap.refreshToken;
          mylib.Datastore.configureWithSessionToken(this.token);
          this.router.navigate(['/signup']);
        },
        onError: function (error) {
          console.error(error);
        }
      });
      console.log(this.token);
      console.log('signinUser Called!');
  }
}

mylib is Javascript library and this is not pointing to my object so this.token is not woking how can i access my class fields in Javascript block?

3
  • I think you will want to call user.token. this refers to the function signinUser since you are calling it outside of the object literal. Also, it appears that user.requestSessionToken is async, so you may need to use a callback or promise to wait until the function is finished before accessing this.token. Commented Aug 4, 2017 at 14:52
  • token is local member in AuthService class not in user Commented Aug 4, 2017 at 14:53
  • Please refer this doc - github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript Commented Aug 4, 2017 at 14:55

1 Answer 1

1

Arrow function is the answer.

export class AuthService {
  token: string;
  refreshToken: string;
  constructor(private router: Router) { }

  signinUser(username: string, password: string) {
      const user = new mylib.User(username, password);
      user.requestSessionToken(true, {
        onOk: (result) => {
          let tokenMap: any;
          tokenMap = result;
          this.token = tokenMap.sessionToken;
          this.refreshToken = tokenMap.refreshToken;
          mylib.Datastore.configureWithSessionToken(this.token);
          this.router.navigate(['/signup']);
        },
        onError: (error) => {
          console.error(error);
        }
      });
      console.log(this.token);
      console.log('signinUser Called!');
  }
}

alternatively (old-school), you can use bind(): (function (result) { ... }).bind(this)

The reason is in the onOK callback, this is probably the user instance, not your class.

Always be careful on what is this when you are dealing with callbacks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.