Route to some other page based on guard in angular 6, rxjx 6 async request

527 views Asked by At

I have implemented the functionality where I am able to get the request and control the authorization of the page, I want to redirect to login page in case of false request.

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authSer.isAuthenticated().pipe(map((response) => {
            console.log('I ma here');
            if (response.status === 200) {
                return true;
            } else {
                console.log('Error getting data');
                return false;
            }
        }), catchError((error) => of(false))
    );
}

How can I route to the login page from here? I am using angular 6

2

There are 2 answers

0
Badashi On

I know the question specifically states Angular 6, I just want to mention that as of angular 7.1 You can return an UrlTree instead or a boolean from your guard - as well as the Promise and Observable equivalents -, and that will serve as an automatic redirect. So in your case:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  return this.authSer.isAuthenticated().pipe(
    map((response) => {
      console.log('I ma here');
      if (response.status === 200) {
        return true;
      } else {
        console.log('Error getting data');
        return false;
      }
    }),
    catchError((error) => of(false)),
    map(responseOk => {
      // Isolate dealing with true/false results since they can come from different opperators
      if (!responseOk) {
        return this.router.createUrlTree(['path', 'to', 'redirect'])
      }
      // alternatively, return a different UrlTree if you feel like it would be a good idea
      return responseOk
    })
  );
}

I also highly recommend upgrading to Angular 7 using their Guide. It's pretty painless and it will enable you with new features as well as bringing a bunch of bugfixes.

0
Алексей Сидоров On

Here example guard with redirect to url. May be it help:

export class AuthGuard implements CanActivate {    
constructor(private router: Router, private authService: AuthenticationService) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isAuth) {
        return true;
    }
    else {
        this.router.navigate([state.url]); // or some other url
    }
}}