Reputation: 83
I have a problem with the function navigate
in the router since a change of angular 2 version. I upgraded the version from 2.0.0-rc.1 to 2.0.0-rc.3
so I had to change the version of the router like this :
@angular/router : 2.0.0-rc.1 to 3.0.0-alpha.7
and I created a file with all the routes in it.
export const routes:RouterConfig = [
{ path: '', component: Home, terminal: true },
{ path: 'home', component: Home },
{ path: 'login', component: Login },
...
and then I added the routes to the bootstrap function
bootstrap(AppComponent, [
AppWebservice,
HTTP_PROVIDERS,
APP_ROUTER_PROVIDERS,
provide(Config, {useClass: Config})
]).catch(err => console.error(err));
I have a component with this code :
ngOnInit() {
console.log('isLoggedin: ' + isLoggedin())
if (isLoggedin()) {
this.router.navigate(['/home']);
} else {
this.router.navigate(['/login']);
}
}
In this component the code this.router.navigate(['/login']);
works nicely with 2.0.0-rc.1 but now it doesn't work with the new version.
I checked the value of isLoggedin()
and when it's value is false I still be re-rerouted to the Home page and not to the Login page.
Does anyone know why the router does not work properly ?
Upvotes: 1
Views: 333
Reputation: 51
This is a basic example of how you should set up a Guard for your routes.
Add canActivate: [HomeGuard]
on the route/s you need redirection.
You will need to create a service for isLoggedin
to be injected into the guard.
And of course create the Guard Injectable.
Let me know if you have any further questions.
export const routes:RouterConfig = [
{ path: '', component: Home, terminal: true, canActivate: [HomeGuard]},
{ path: 'home', component: Home },
{ path: 'login', component: Login },
@Injectable()
export class HomeGuard implements CanActivate {
constructor(provate isLoggedinService: IsLoggedinService, private router: Router) {}
canActivate() {
console.log('this.isLoggedinService.isLoggedin: ' + this.isLoggedinService.isLoggedin())
if (this.isLoggedinService.isLoggedin()) {
this.router.navigateByUrl('home');
return false;
} else {
this.router.navigateByUrl('login');
return false;
}
}
}
Upvotes: 0