【问题标题】:Does the routing paths order matter in angular?路由路径的顺序在角度上是否重要?
【发布时间】:2022-02-14 15:07:42
【问题描述】:

我正在尝试为我的一个组件制作路由器,但它没有按预期工作。

最初它工作正常,但我不得不添加另一条路线来决定在重定向时打开哪个 mat-tab。我像这样添加了第二条路线,但由于某种原因,第三条路线停止工作,尽管前两条路线运行良好。

import { Routes } from '@angular/router';
import { ActionComponent } from './action.component';
import { ActionResolver } from './action.resolver';
import { ACTION_RESULT_ROUTES } from './result/action-result.routes';

export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
];

我在尝试第三条路线时遇到了一个非常大的错误,但它开始时是这样的:

ERROR 错误:未捕获(承诺中):TypeError:您在预期流的位置提供了“null”。您可以提供 Observable、Promise、ReadableStream、Array、AsyncIterable 或 Iterable。

以防万一,我尝试重新排序,当我这样做时所有三个都工作正常:

export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
];

谁能告诉我为什么会这样?

编辑:添加了 ACTION_RESULT_ROUTES 以进行澄清

export const ACTION_RESULT_ROUTES: Routes = [
  { path: ':id', component: ActionResultComponent, resolve: { result: ActionResultResolver } },
];

【问题讨论】:

  • 你如何访问你的 url 中的第三条路由?
  • @GRD action-result/XX (xx 是 ID 号),路由就像第一个使用 ID 的路由,但它会导致不同的组件并使用不同的解析器,我会将其添加到问题中

标签: html angular typescript routes


【解决方案1】:

根据 Angular:

“路由的顺序很重要,因为路由器使用 匹配路线时,first-match 获胜策略,因此更具体 路线应该放在不太具体的路线之上。”

建议首先使用静态路由,因此您的action-result 路径应该先行,然后是:id/:tab 路径,然后是:id 路径。如果您有通配符路由,则它应该始终是数组中的最后一个路由。

此逻辑背后的原因是,如果您在 action-result 路径上方有 :id 路径,则 Angular 将使用单词“action-result”作为 :id 路径中的 id。 同样,如果 :id 路径位于 :id/:tab 路径上方,则 Angular 将使用单词 id/tab 作为 :id 路径中的 id。

因此,经验法则是始终将静态路由放在首位,然后是动态路由(从最具体到最不具体),最后是通配符路由。 如:

  • PATH1
  • PATH2
  • PATH3/:USER/:ROLE/:PAGE
  • PATH4/:SITE/:ID
  • PATH5:/ID
  • 通配符路由 (*)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多