Angular2 - Redirect to calling url after successful login

后端 未结 3 1029
说谎
说谎 2020-11-28 09:30

I have my application up and running with Angular 2.1.0. The routes are protected via router Guards, canActivate.

When pointing the browser to a protected area like

3条回答
  •  萌比男神i
    2020-11-28 09:44

    This code will handle your request:

    export class AuthGuard implements CanActivate {
      constructor(private authService: AuthService,
                  private router: Router) {
      }
    
      canActivate(next: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): Observable {
        return this.authService.isVerified
          .take(1)
          .map((isVerified: boolean) => {
            if (!isVerified) {
              this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
              return false;
              // return true;
            }
            return true;
          });
      }
    }

    but be aware that the URL params will not pass with the URL!!

    You can find a nice tutorial here : http://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard

提交回复
热议问题