I am trying to set up authentication for my Angular 2 app with the new router. Someone suggested to try the following:
constructor (private _router: Router) {}
ngOnInit(){
this._router.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
This problem however is that this results in the typescript error
(appponent.ts(47,22): error TS2339: Property 'subscribe' does not exist on type 'Router'.
This is strange because the documentation clearly shows that a Router object does have this function. I am able to call other functions like router.navigate(['/url']). Do you guys have an idea what could be the problem?
I am trying to set up authentication for my Angular 2 app with the new router. Someone suggested to try the following:
constructor (private _router: Router) {}
ngOnInit(){
this._router.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
This problem however is that this results in the typescript error
(app.ponent.ts(47,22): error TS2339: Property 'subscribe' does not exist on type 'Router'.
This is strange because the documentation clearly shows that a Router object does have this function. I am able to call other functions like router.navigate(['/url']). Do you guys have an idea what could be the problem?
Share Improve this question edited May 10, 2016 at 11:41 Thierry Templier 202k44 gold badges405 silver badges364 bronze badges asked May 10, 2016 at 11:39 hY8vVpf3tyR57XibhY8vVpf3tyR57Xib 3,9158 gold badges50 silver badges96 bronze badges1 Answer
Reset to default 7new router
constructor(router:Router) {
router.events.subscribe(event:Event => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
})
}
original
The Router
class has an EventEmitter
changes
you can subscribe to:
ngOnInit(){
this._router.changes.subscribe(
next => {
if (!userIsLoggedInOrWhatever) {
this._router.navigate(['Login']);
}
}
)
}
For how to get the previous route see How to detect a route change in Angular 2? (pairwise()
)