javascript - Angular 2+ 路由 redirectTo 作为函数
我在 Angular 应用中有以下路由配置:
{
path: ParentComponent.path,
component: ParentComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
pathMatch: 'full',
redirectTo: getDefaultChildRoute()
},
{
path: ':mode/:year/:month/:day',
component: ChildComponent
}
]
}
getDefaultChildRoute() 函数返回一个类似这样的字符串:
export function getDefaultChildRoute(): string {
const urlArray = ['a', '2019', '02'];
return urlArray.join('/');
}
问题似乎在于 redirectTo 期望的是一个字符串,而不是一个可调用的方法(即使它返回的是字符串)。如果我将该方法调用替换为一个占位字符串,它就能正常工作。
关于它在 GitHub 上已经有一个问题了:https://github.com/angular/angular/issues/13373
在 redirectTo 上直接使用箭头函数会抛出 Typescript 错误 '()=>string 不能分配给类型 string'。
有什么想法吗?
答案#1
试试这个:
redirectTo: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const urlArray = ['a', '2019', '02'];
return urlArray.join('/');
}
