Reputation: 269
I am trying to navigate to another path in AppComponent on startup and it does not seem to work. In my app.component, I am trying to navigate in my ngOnInit method:
export class AppComponent implements OnInit {
constructor(private _router: Router) {
}
ngOnInit() {
console.log("IN ngOnInit!!!!!!!!!!!!!!!!!!!!");
this._router.navigate(["/login"]).then( () => console.log("DONE Navigation!!!!!!!!!!!!!!!!!!!!")).catch(err => console.log("Error!!!!!: " + err));
console.log("GOING OUT ngOnInit!!!!!!!!!!!!!!!!!!!!");
}
}
In my main.ts, I bootstrap the component:
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS
]).then(() => console.log("DONE BOOTSTRAP"));
And the console output is:
IN ngOnInit!!!!!!!!!!!!!!!!!!!!
GOING OUT ngOnInit!!!!!!!!!!!!!!!!!!!!
DONE Navigation!!!!!!!!!!!!!!!!!!!!
DONE BOOTSTRAP
My guess is that the navigation can't be performed because the bootstrap is not complete for the APP_ROUTER_PROVIDERS. Are there any events that I can hook onto so that I can call the navigate after the bootstrap is complete? I am on Angular 2 RC4.
Thanks in advance!
Upvotes: 1
Views: 877
Reputation: 906
For the moment you cannot call the navigate function in the OnInit of the main component. This is due to a bug cause by this https://github.com/angular/angular/blob/master/modules/@angular/router/src/common_router_providers.ts#L54-L61
There's a issue open open on github: https://github.com/angular/angular/issues/9101
For the moment, the quick fix would be to put your navigate call in a setTimout()
function.
Upvotes: 1
Reputation: 136184
Ideally you should give the responsibility of redirection to angular router itself. Add one route which will be responsible for redirecting ''
(blank) to /login
page, when there is no specific route matched.
{
path: '', //blank will redirectTo `/login`
redirectTo: '/login',
pathMatch: 'full'
},
Upvotes: 2