I have created an authentication service in which I check the presence of access token in a local storage. For that I have created an observable which calls a hasValidAccessToken
function. The function emits the boolean
value.
I make the subscription to that observable in app-component
. The issue is I am not able to unsubscribe the subscription in app-component
because it never gets destroyed.
authentication.service.ts
public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(this.hasValidAccessToken());
public isAuthenticated$: Observable<boolean>;
isTokenExpired(): boolean {
const expiresAt = localStorage.getItem("expires_at");
const now = new Date();
if (
expiresAt &&
parseInt(expiresAt, 10) < Math.floor(now.getTime() / 1000)
) {
return false;
}
return true;
}
hasValidAccessToken(): boolean {
if (this.hasAccessToken()) {
return this.isTokenExpired();
}
return false;
}
hasAccessToken(): boolean {
return !!localStorage.getItem("access_token");
}
decodeToken(token: string) {
if (token) {
return jwt_decode(token);
}
}
app.component.ts
this.isAuthenticatedSubscription = this.oauthService.isAuthenticated$.subscribe(
data => {
if (data) {
this.router.navigate(["home"]);
} else {
this.router.navigate(["login"], {
state: { data: "session has been expired" }
});
}
}
);
this.isAuthenticatedSubscription.unsubscribe()
? what error do you get? - Vivek DoshicanActivate
. Angular Authentication using Guards - Dino