0

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}
];
5
  • What version of Angular are you using? Do you have the routes configured? Are you importing them properly (depending on which version you have)? We'll need more information to help you out Commented Aug 30, 2016 at 13:52
  • The routes are configured, RC.5. I added my app.routes.ts, The HomeCOmponent is loaded Although I am navigating with this.router to intro Commented Aug 30, 2016 at 14:07
  • Please paste a minimal example into a plunker. Commented Aug 30, 2016 at 14:17
  • @TheUnreal : Have you got any solution for this?? Commented Sep 1, 2016 at 3:41
  • @sachinkulkarni nope I have not used this way Commented Sep 1, 2016 at 9:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.