When the user is tries to search an unknown url path its navigating to the log-in page.But the token is not getting cleared from the local storage

Issue

This Content is from Stack Overflow. Question asked by Agnum

Here removeItem is added to remove the userdata from localstorage if the user tries to search an unknown path but its not clearing the data.A solution would be great help

    import { Injectable } from "@angular/core";
    import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from "@angular/router";
    import { Observable } from "rxjs";
    import { map, tap,take } from "rxjs/operators";
    import { AuthServices } from "./auth-services";
    
    @Injectable({ providedIn:'root'})
    export class AuthGuard implements CanActivate{
        constructor(private auth:AuthServices,private router:Router){}

         canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot):boolean|UrlTree | Observable<boolean |UrlTree> | Promise<boolean |UrlTree>{
                 return this.auth.tokenCredential.pipe
              (take(1),
               map(res=>{
               if(res){ 
               if(this.router.url==='**'){
               localStorage.removeItem('tokenKey')
               this.router.navigate(['/log-in'])
                 }
               return true
                  }
    
             return this.router.createUrlTree(['/log-in'])

  
                   }
  
                   )
                   )
                   }
                   }



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?