Reputation: 1387
I can define a static redirect in the routes array
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', component: ProductsComponent },
];
We are using the redirectTo
to tell angular route service if the users navigate to the empty URL they should be redirected to the home URL rather than the empty URL.
I need that rule to be dynamic. Depending on the condition, I need to redirect the user to the products page instead of the home page.
Upvotes: 1
Views: 3690
Reputation: 1387
I created a separate service which listens to router event RouteRecognised and redirects when it's necessary.
this.router.events
.pipe(filter(event => event instanceof RoutesRecognized))
.subscribe((e: RoutesRecognized) => {
if (condition) {
this.router.navigateByUrl((newUrl, { replaceUrl: true });
}
});
Upvotes: 0
Reputation: 736
You can use custom guard which implements CanActivate. You should add it to route like this:
canActivate: [AuthGuard]
and then redirect to route you want to depending on dynamic conditions.
Example at Angular docs (auth guard).
Upvotes: 0