0

I've defined a resolver for my signup route:

import {IsLoggedin} from './share/is-loggedin.service';

const appRoutes: Routes = [
    {path: 'signup', resolve: [IsLoggedin], component: SignupComponent}
]

In the resolver I'm redirecting to a certain page if the user is logged in:

resolve(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
    this.authService.isUserAuthenticated()
               .subscribe(
                   (res: any) => {
                       if (res === true) {
                           this.router.navigate(['/main-board']);
                       }
                   }
               );
}

But, angular loads the SignupComponent anyway before redirecting to the main-board page.

Note: I've tried with CanActivate guard, but it still can't redirect without loading the componenet as isUserAuthenticated() method returns a Observable and doesn't work synchronized way.

I really want to know whether it is possible in angular to redirect to the main-board page without loading the SignupComponent.

Can it be done smoothly in angular 2/4 ?

I would really appreciate if someone help me.

2
  • 4
    Consider using guards for your case. Maybe a CanActivate guard ? angular.io/api/router/CanActivate Commented Aug 27, 2017 at 20:32
  • CanActivate guard still it can't redirect without loading the componenet as isUserAuthenticated() method returns a Observable and doesn't work synchronized way Commented Aug 28, 2017 at 2:20

1 Answer 1

1

If CanActivate guard is used instead of Resolve then the redirection will be smooth. Then it won't load the route component SignupComponent before the redirection:

import {IsLoggedin} from './share/is-loggedin.service';

const appRoutes: Routes = [
    {path: 'signup', canActivate: [IsLoggedin], component: SignupComponent}
]

The the is-loggedin.service.ts :

canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
    /* this.authService.isUserAuthenticated() return an http Observable */
    return this.authService.isUserAuthenticated()
               .map((res: any) => {
                       if (res === true) {
                           this.router.navigate(['/main-board']);
                           return false;
                       }
                       return true;
                   }
               );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.