Angular2 - Redirect to calling url after successful login

后端 未结 3 990
说谎
说谎 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 09:47

    The answers I saw were correct. But the best way to answer your question is returnUrl. like this:

    export class AuthGuardService implements CanActivate {
    
      constructor(private auth: AuthenticationService, private router: Router) { }
    
      canActivate(next: ActivatedRouteSnapshot,
        _state: import('@angular/router').RouterStateSnapshot): Observable | Promise | boolean {
        let isLoggedIn = false;
        const idToken = next && next.queryParamMap.get('id_token');
        try {
          const expiresAt = idToken && JSON.parse(window.atob(idToken.split('.')[1])).exp * 1000;
          if (idToken && expiresAt) {
            isLoggedIn = true;
            localStorage.setItem('id_token', idToken);
            localStorage.setItem('expires_at', String(expiresAt));
          } else {
            isLoggedIn = this.auth.isLoggedIn();
          }
        } catch (e) {
          console.error(e);
          isLoggedIn = this.auth.isLoggedIn();
        }
        if (!isLoggedIn) {
          //this section is important for you:
          this.router.navigate(['/login'], { queryParams: { returnUrl: _state.url }});
        }
        return isLoggedIn;
      }
    }
    

    This navigate create a url with returnUrl like a param, now you can read returnUrl from param.

    GoodLuck.

提交回复
热议问题