0

I'm able to get the value for the token after logging in because I'm passing in the values for the username and password from a function. On the next page, I'm not passing in those values. Which makes sense as to why I'm getting null. So is the most efficient way for getting that value is passing the username and password from page to page and calling that function?

Auth.ts

login(userName: string, password: string, route: string = null): any {
    this.logout(false);

    this.doLogin(userName, password)
      .subscribe(response => {
        let token:string = JSON.stringify(response.access_token);
        this.storage.set('token', token);
        console.log(token, 'this is the token here')

      });
  }

getToken(){
  this.storage.get('token').then((val) => {
        this.accessToken = val;
         })


         if(this.accessToken == undefined || this.accessToken == null){
              return '0'
         }
            else{
                return "Bearer " + this.accessToken.replace(/["]+/g, '')
            }
}

component.ts

login(){
this.authService.login(this.account.username, this.account.password)
}

Interceptor.ts

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        let access = this.auth.getToken()

        const authReq = req.clone({
                setHeaders: {
                Authorization: access
                }
        });

    return next.handle(authReq)
  }

Thanks!

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
userlkjsflkdsvm
  • 961
  • 1
  • 21
  • 53

1 Answers1

0

Your code is asynchronous.

this.storage.get('token').then((val) => {
  this.accessToken = val;
})

if(this.accessToken == undefined || this.accessToken == null){
  return '0'
} else {
  return "Bearer " + this.accessToken.replace(/["]+/g, '')
}

Here, the first thing that happens is that you register that you want something to happen once getting token is completed (first block).

Then, you execute the if/else statements below. this.accessToken is always undefined here.

The, once token is fetched, the code inside the then callback is run, setting accessToken only after that.

You can confirm this behvaior if you put a few console.logs here and there.


You need to put the code dependant on the token fetched asynchronously inside the promise callback, like this.

this.storage.get('token').then((val) => {
  this.accessToken = val;

  if(this.accessToken == undefined || this.accessToken == null){
    return '0'
  } else {
    return "Bearer " + this.accessToken.replace(/["]+/g, '')
  }
})

As a side note, this.accessToken == undefined and this.accessToken == null are equivalent. It's enough to write only one of those; people usually write only this.accessToken == null to keep it short.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
  • I'm getting this error when making that adjustment - ERROR TypeError: Cannot read property 'length' of undefined. Also had to change getToken(): any {}<<----- – userlkjsflkdsvm Sep 01 '17 at 18:53
  • Just copy/pasting a snippet from an answer will not make your code magically work. Try to understand issue you had and apply the same technique in the rest of your code, there are likely similar errors. `.length` doesn't even appear in the above code. – Lazar Ljubenović Sep 01 '17 at 18:55
  • Appreciate the help! I'm getting ERROR TypeError: Cannot read property 'then' of undefined, the token is undefined because the user hasn't entered in their credentials. How would I go about making it so that this function is only called when the user has entered in their credentials. – userlkjsflkdsvm Sep 01 '17 at 19:30