Reputation: 179
I need to conditionally route to 2 pages in my angular app ,
My Route.ts file
const routes: Routes = [
{ path: '', redirectTo: 'exampleInfo', pathMatch: 'full' },
{ path: 'invalid', component:InvalidComponent},
Somewhere in the app i am setting the router to navigate to 'invalid' based on some condition . Now when i hit my URL , it opens the exampleInfo page for a fraction of a second and then redirects to invalid component .
How can i directly navigate to invalid component without hitting the default component conditionally ?
Thanks in advance .
Upvotes: 1
Views: 4383
Reputation: 213
You can create a router guard with canActivate
In the canActivate
function you can check the condition. If its invalid you can route to your InvalidComponent
else the guard let you go through the normal page.
const routes: Routes = [
{ path: '', redirectTo: 'exampleInfo', canActivate: [YourGuard], pathMatch: 'full' },
{ path: 'invalid', component:InvalidComponent},
This will happen befor you even enter the exampleInfo
page.
Upvotes: 3
Reputation: 1072
If your invalid component has a specific set of conditions that should trigger showing it, consider using a route guard on the pages that should not be accessible in this state that re-routes to the invalid component.
The advantage of this is that you seperate your "where should a user be" logic from the templates themselves, so your component won't initialise before it realises the user shouldn't be there.
Upvotes: 0
Reputation: 178
There is also the possibility to switch the components in the routes array. Could this be of help to you?
const routes: Routes = [
{ path: '', redirectTo: 'exampleInfo', pathMatch: 'full' },
{ path: 'invalid', component:InvalidComponent},
{ path: 'exampleInfo', component: (() => {
return SomeService.staticMethod() ? ExampleInfoComponent : InvalidComponent;
})() }
...
]
edit: However, as you may see, for this solution you need to be able to offer a static method, e.g. in a service, but a component should work as well, that can return true/false.
Upvotes: 2
Reputation: 156
You can use below :
const routes: Routes = [
{ path: 'SomePath', redirectTo: 'exampleInfo', pathMatch: 'full' },
{ path: 'invalid', component:InvalidComponent},
{ path: '**', component:InvalidComponent}
you can use some path for example info and add last line any other route will take you to invalid component.
Upvotes: 0