【问题标题】:Angular 2+ route redirectTo as a functionAngular 2+路由redirectTo作为函数
【发布时间】:2019-09-15 20:15:39
【问题描述】:

我在 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 is not assignable to type string'。

有什么想法吗?

【问题讨论】:

  • 一个函数对我有用,箭头不起作用,因为你没有让它自我执行,调用它像:(() => {})()。见这里stackblitz.com/edit/…
  • 它以某种方式在点击时起作用,但在加载时不起作用?.. 尝试像您说的那样调用箭头函数 - 没有类型错误,但它仍然不会重定向。
  • 您使用的 Angular 版本是什么?我尝试了一条空路径,但它仍然可以在负载上运行。见:stackblitz.com/edit/angular-k95xjv?file=src/app/app.module.ts
  • Angular 7.2.1 + Typescript 3.3.3 嗯,这很奇怪。
  • @xyz:它确实工作了一段时间!但是,当使用 AOT 标志编译时,它会失败并显示以下消息:ERROR in Error during template compile of 'AppRoutingModule' Function calls are not supported in decorators but 'getDefaultChildRoute' was called in 'appRoutes' 'appRoutes' calls 'getDefaultChildRoute' at app/app-routing.module.ts(67,42). 我需要提供它,但语法不正确。 (如果您回复,请将其写为答案,这样我就可以投票并将其标记为正确,如果是的话;))

标签: javascript angular typescript angular2-routing


【解决方案1】:

试试这个:

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

【讨论】:

  • 不,这就是我对箭头函数的意思。我收到 TS2322 错误:type() => string is not assignable to type 'string'
猜你喜欢
  • 2017-01-25
  • 1970-01-01
  • 2017-10-21
  • 2017-06-04
  • 2021-02-20
  • 2018-10-02
  • 2021-11-05
  • 1970-01-01
  • 2017-01-07
相关资源
最近更新 更多