Answer the question
In order to leave comments, you need to log in
How to properly use BehaviorSubject/Observable in guard?
Application on Ionic 5 / Angular 9. Ionic Data Storage
is used for data storage .
auth.guard looks like this:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '@app/_services'
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const accessToken = this.authService.currentTokenValue;
if(accessToken) {
return true;
}
this.router.navigate(['/login'])
return false;
}
}
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage'
import { BehaviorSubject, Observable, from } from 'rxjs'
import { map } from 'rxjs/operators';
import { Token } from '@app/_models'
import { environment } from '@env/environment';
@Injectable({
providedIn: 'root'
})
export class AuthService {
currentTokenSubject = new BehaviorSubject(null)
constructor(
private http: HttpClient,
private storage: Storage,
) {
this.getToken()
}
getToken() {
this.storage.get('accessToken').then(res => {
if (res) {
this.currentTokenSubject.next(res)
}
})
}
public get currentTokenValue(): string {
return this.currentTokenSubject.value;
}
login(username: string, password: string) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + btoa(username + ':' + unescape(encodeURIComponent(password)))
})
return this.http.post<Token>(`${environment.apiUrl}/auth/signin`, { }, { headers })
.pipe(map((res: Token) => {
let token = res.token
// store user details and jwt token in local storage to keep user logged in between page refreshes
this.storage.set('accessToken', token);
return token;
}));
}
logout() {
// remove user from local storage to log user out
this.storage.remove('accessToken');
this.currentTokenSubject.next(null);
}
}
import { Injectable } from '@angular/core'
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'
import { Observable } from 'rxjs'
import { AuthService } from '@app/_services'
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const currentToken = this.authService.currentTokenValue;
if (currentToken) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentToken}`
}
});
}
return next.handle(request);
}
}
Answer the question
In order to leave comments, you need to log in
Application is initialized, auth.guard is checked and currentTokenValue() returns null
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question