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
!
Use RouterStateSnapshot in the auth guard to capture the requested URL.
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.
You might find what you need in the docs for the
Location
class. Theback()
function could possibly do it for you.Another approach would be to subscribe to the
popstate
events inLocation
, instead. MDN has docs talking about the values you could expect to receive.Otherwise you might want a service that tracks the changes in the Router so that you can access them.
In this case I'm accessing the
Router
object and subscribing to any changes so that I could track them.This worked for me. Inject it into your main App component's constructor having registered it in the bootstrap method. The first
val
on page load should be the original URL. I am unsubscribing right after to be efficient since I don't (perhaps, yet) want to listen to subsequent router events in this service. Inject the service into other places where originalUrl is needed.Updated Example Using Angular 2.2.1
Auth Guard that passes original URL to login component:
Login Component that redirects to the previous / original URL after login:
For more details and working demo you can check out this post