-2

I have a property token, I would like to initialize it in a calback of a method.

Unfortunately, I got this message

Cannot set property 'token' of undefined

when I try to put the value of access_token in the property token

public token:string = "";
  signInAction(){
    new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) {
         console.log(user.access_token);
         this.token = user.access_token;
    }).catch(function (e) {
        console.error(e);
    });
  }

Any idea why.

Jean-Francois
  • 1,809
  • 4
  • 31
  • 72
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – trincot Apr 28 '17 at 21:28
  • 3
    This is a duplicate question. `this` in the callback function does not refer to what you think it does. There are many ways to get around this. Read the referenced Q&A. – trincot Apr 28 '17 at 21:28
  • Possible duplicate of [Javascript Closures and 'this'](http://stackoverflow.com/questions/346015/javascript-closures-and-this) –  Apr 29 '17 at 03:48
  • This has nothing to do with Angular, or promises for that matter. It's just basic JS and is the same problem that has existed for twenty years. –  Apr 29 '17 at 03:50

1 Answers1

0

Please read the URL trincot mentioned to learn how this works inside callbacks. In your case, I think the following should work:

public token:string = "";

signInAction(){
  new Oidc.UserManager(this.config)
    .signinRedirectCallback()
    .then(user => {
      console.log(user.access_token);
      this.token = user.access_token;
     })
     .catch(e => {
       console.error(e);
     });
}
André
  • 11,699
  • 5
  • 39
  • 40