1

Let's say, I make a post request to create my token.

public tokenInfo: TokenInfo;

public login(creds){
   return this.http.post<TokenInfo>(this.baseUrl + "Account/CreateToken", creds)
          .map(res =>{
                this.tokenInfo = res;  
                return true;                      
          })
  }

I get back my token and the expiration date. something like:

{token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ...", expiration: "2017-12-04T03:40:55Z"}

How do I keep it around so that other component can take advantage of it? The first thing that comes to mind is to display the name of the logged user at the left corner of the menu bar and hide the Login item.

Thanks for helping

Richard77
  • 20,343
  • 46
  • 150
  • 252

2 Answers2

1

You can save your token in the web storage like this:

window.localStorage.setItem('token', res.token);

And you can get it later like this:

window.localStorage.getItem('token');
Petrus Cyrino
  • 204
  • 2
  • 5
1

I would use a service for this purpose:

@Injectable()
export class AuthService {
  authToken: TokenInfo;

  public login(creds) {
    // You could store the auth token in local storage here instead.
    return this.http.post('/login').subscribe((res) => this.authToken = res);
  }

  public getAuthToken() {
    return this.authToken;
  }
}

export class YourComponent {
  constructor(private authService: AuthService) { }

  login() { 
    this.authService.login({ /* Your credentials. */ });
  }

  displayToken() {
     alert(this.authService.getAuthToken());
  }
}
ACOMIT001
  • 510
  • 1
  • 7
  • 21
  • So, do you mean that `AuthService ` won't be re-created each time the a new component is created? I really like this idea. – Richard77 Dec 04 '17 at 23:02
  • 1
    It won't be re-created if you're injecting the service in the providers definition of your app.module file. Have a look at this for more information: https://stackoverflow.com/q/36198785/3713362 – ACOMIT001 Dec 05 '17 at 00:48