Angular 2+路由redirectTo作为函数

时间:2019-04-26 10:20:03

标签: javascript angular typescript angular2-routing

我在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错误'()=>字符串不可分配给字符串类型'。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试一下:

redirectTo: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
    const urlArray = ['a', '2019', '02'];
    return urlArray.join('/');
}