Angular 2 AuthGuard Service with redirect?

前端 未结 5 1159
南旧
南旧 2020-12-05 22:46

I have an application that I am building that implements CanActivate on the dashboard route. It works fine accept on page reload, I check a flag in the user service to see i

5条回答
  •  执笔经年
    2020-12-05 23:36

    Here's how to correctly handle redirects in a guard by using an UrlTree

    @Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivateChild {
      constructor(
        private authService: AuthService,
        private logger: NGXLogger,
        private router: Router
      ) {}
    
      canActivateChild(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable {
    
        return this.authService.isLoggedIn().pipe(
          map(isLoggedIn => {
            if (!isLoggedIn) {
              return this.router.parseUrl('/login');
            }
    
            return true;
          })
        );
      }
    }
    

    Big thanks to Angular In Depth for the explanation!

提交回复
热议问题