路由中的条件重定向
Conditional redirectTo in routes
我可以在路由数组中定义静态重定向
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', component: ProductsComponent },
];
我们正在使用 redirectTo
告诉 angular 路由服务如果用户导航到空 URL 他们应该被重定向到家 URL 而不是空 URL.
我需要该规则是动态的。根据情况,我需要将用户重定向到产品页面而不是主页。
您可以使用实现了 CanActivate 的自定义守卫。你应该像这样将它添加到路由中:
canActivate: [AuthGuard]
然后根据动态条件重定向到您想要的路线。
示例位于 Angular docs(auth guard)。
我创建了一个单独的服务来侦听路由器事件 RouteRecognised 并在必要时重定向。
this.router.events
.pipe(filter(event => event instanceof RoutesRecognized))
.subscribe((e: RoutesRecognized) => {
if (condition) {
this.router.navigateByUrl((newUrl, { replaceUrl: true });
}
});
我可以在路由数组中定义静态重定向
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', component: ProductsComponent },
];
我们正在使用 redirectTo
告诉 angular 路由服务如果用户导航到空 URL 他们应该被重定向到家 URL 而不是空 URL.
我需要该规则是动态的。根据情况,我需要将用户重定向到产品页面而不是主页。
您可以使用实现了 CanActivate 的自定义守卫。你应该像这样将它添加到路由中:
canActivate: [AuthGuard]
然后根据动态条件重定向到您想要的路线。
示例位于 Angular docs(auth guard)。
我创建了一个单独的服务来侦听路由器事件 RouteRecognised 并在必要时重定向。
this.router.events
.pipe(filter(event => event instanceof RoutesRecognized))
.subscribe((e: RoutesRecognized) => {
if (condition) {
this.router.navigateByUrl((newUrl, { replaceUrl: true });
}
});