Reputation: 24462
I have the following expression if the user is a guest:
this.router.navigate(['/intro']);
in my app.component.ts ngOnInit()
method.
My app.component.html has <router-outlet></router-outlet>
but when I access my app as guest, the IntroComponent
is not displayed and the URL stays empty without the /intro
.
What's wrong?
my app.routes.ts
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{path:'intro',component: IntroComponent},
{path:'login',component: LoginComponent},
{path:'register', component: RegisterComponent}
];
Upvotes: 0
Views: 510
Reputation: 40647
Change your routes like this:
const appRoutes: Routes = [
{ path: '', redirectTo: HomeComponent, pathMatch: 'full'}, //(redirectTo or component)
{path:'intro',component: IntroComponent},
{path:'login',component: LoginComponent},
{path:'register', component: RegisterComponent}
];
the default pathMatch
strategy is prefix
in routes so path: ''
with prefix
means practically everyroute. So everyroute was navigated to the HomeComponent
.
Upvotes: 1
Reputation: 4787
This happens because initial navigation is not completed when calling this.router.navigate(['/intro'])
from ngOnInit
.
There are two ways to solve this:
Solution #1
In app.module.ts
you disable initial navigation
RouterModule.forRoot(appRoutes, { initialNavigation: false })
Ref: router.navigate failing silently on OnInit of component
Solution #2
If you do not want to disable initial navigation then use setTimeout
to allow the initial navigation to complete.
setTimeout(() => this.router.navigate(['/intro']), 1)
Upvotes: 0