Angular – Using Angular2, how to redirect to previous url before login redirect

angularangular2-routingredirect

Using Angular2 to create a single page app, I'm intercepting unauthenticated user access to non-public routes in a custom RouterOutlet and redirecting them to a login view. After a successful login, I want to redirect the user to their originally requested view, rather than the default view.

I've noticed that Router has a renavigate() function that navigates to the last successful route BUT the last successful route was /auth/login and not the originally requested url.

Basically : How can I access, or determine the previously requested url?

I don't really want to resort to passing query string parameters around, unless I really have to. Ideally it would be nice to have access to history collection as part of the Router component, similar to backbone.history!

Best Answer

  1. Use Auth Guards (implements CanActivate) to prevent unauthenticated users. See official documentation with examples and this blog.
  2. Use RouterStateSnapshot in the auth guard to capture the requested URL.

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
    {
        // keep the attempted URL for redirecting
        this._loginService.redirectUrl = state.url;
    }
    
  3. Redirect to that URL on successful authentication with using Router (e.g. in the login.component.ts). E.g. this._router.navigateByUrl(redirectUrl);

P.S. Suggestions of @MichaelOryl and @Vitali would work, but my way is more aligned with Angular2 final release.