In Angular 2, you can specify a @CanActivate
annotation for a component where you can determine if the component should be activated or not. The reason it's not an interface is because the callback is called before the component is even instantiated. The problem is, I can't figure out a way to get dependencies injected into that callback. And I need my service that tells me whether I'm logged in or not (and as whom) to determine whether routing to a particular component is allowed or not.
How can I inject a dependency into a @CanActivate callback? I'm using ES5, and this doesn't work:
app.ListsComponent = ng.router.CanActivate([
app.SessionService,
function(session, instruction) {
console.log(session);
return true;
}
])(app.ListsComponent);
Edit: Alternatively, I can use the routerOnActivate
lifecycle event on the component, and use this.router.navigate
to send the user away if they're not supposed to be there. The downside there is that it breaks browser history: If I redirect you asynchronously every time you arrive at a particular URL, you can't use the Back button in your browser very usefully. Is there a way to have router.navigate
use history.replaceState
instead of history.pushState
for this kind of situation?