I have a setup that is 'Services.Module' that knows about injectable services. It is loaded into 'app.module' under 'imports'. Everything works and the app functions fine with calls to endpoints on multiple services. However on an authorization service I have a call similar to:
@Injectable()
export class AuthService {
private endpoint = `${environment.baseApi}/auth`;
private headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
//Can set this to a regular instance variable and same problem occurs
public static jwt: JWT;
constructor(private http: HttpClient) { }
public createAuthToken(user: UserModel): Observable<JWT> {
return this.http.post<JWT>(`${this.endpoint}/createUserToken`, user, { headers: this.headers})
}
get getJWT() {
return AuthService.jwt;
}
}
I call it with a login component like:
.subscribe((str: string) => {
...
var u = ...
this.authService.createAuthToken(u)
.subscribe((jwt: JWT) =>
{
//works just fine
AuthService.jwt = jwt;
this.router.navigate(['/Category']);
})
A route guard is setup for the routes like so:
path: 'Category',
canActivate: [LoginGuard],
component: CategoryComponent
The guard gets hit and all is right with the world with it loading up as shown below:
@Injectable()
export class LoginGuard implements CanActivate, CanLoad {
constructor(private authService: AuthService,
private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.checkLoggedIn(state.url);
}
canLoad(route: Route): boolean {
return this.checkLoggedIn(route.path);
}
checkLoggedIn(url: string): boolean {
console.log(`jwt is: ${this.authService.getJWT}`);
if(this.authService.getJWT != null) {
return true;
}
console.log("Must be logged in first");
this.router.navigate(['/login']);
return false;
}
}
The problem is if I am on a browser and then MANUALLY do (root)/Category the static variable of 'jwt' on AuthService is set to undefined. If I want to persist a variable that I can set and reset GLOBALLY and REFERENCE IT without it turning into an instance that gets reset for a guard what is best practice in Angular 6? I basically want to just go 'token you are now blahblahblah', until I refresh the browser or restart the application I expect your state to stay the same.