I'm facing an issue with Angular Guards and subscriptions. I have an AuthGuard where I want to unsubscribe from a subscription once the loading is false. However, even after implementing the unsubscribe logic, the subscription continues to be called when I change the page.
Here's a snippet of my AuthGuard code:
export class AuthGuard {
private subscription = new Subscription();
constructor(
private router: Router,
private loginService: LoginService,
protected globalMessage: GlobalMessageService
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
console.log(state.url);
// Check if the route contains "/login" and a "token" parameter
if (state.url.includes('/login/validation-compte') && next.queryParams['token']) {
// Call a method to validate the token (replace this with your actual method)
const isValidToken = this.validateToken(next.queryParams['token']);
return true;
}
return true; // Allow navigation for other routes
}
private validateToken(token: string) {
// Replace this with your actual token validation logic
// Return true if the token is valid, false otherwise
this.subscription = this.loginService.validateRegistration(token).subscribe((validateObject: any) => {
console.log("here", validateObject);
if (validateObject.loading === false) {
if (validateObject.error.error.errors[0].type === "TokenInvalidatedError") {
this.globalMessage.add(
{ key: 'loginForm.activation.TokenInvalidatedError' },
GlobalMessageType.MSG_TYPE_ERROR
);
} else if (validateObject.error === false) {
this.globalMessage.add(
{ key: 'loginForm.activation.OK' },
GlobalMessageType.MSG_TYPE_CONFIRMATION
);
}
// Unsubscribe after processing the result
this.subscription.unsubscribe();
}
});
}
}
I've tried to unsubscribe within the validateToken method, but the subscription is still active after changing the page. Any insights into why this might be happening and how I can ensure the subscription is unsubscribed when the page changes?
loginService.validateRegistration(...) is a method that triggers an HTTP call. Depending on the returned object, I perform an unsubscription action. After the completion of the HTTP call, I evaluate the response whether it indicates an error or not. Here's an example of the returned object from this method: {data: undefined, error: false, loading: true} during loading, and {data: data, error: false, loading: false} upon completion.