Angular : 如何管理特定树的 URL

Angular : How to manage the URL of a particular tree

我有一个文件夹主页。每个文件夹都包含一个待办事项列表,每个待办事项列表都包含有自己页面的任务。这是三个(下)。 显然,每个文件夹和每个任务都有一个ID。

我有点不知道如何使用 angular 管理参数和嵌套路由。我正在考虑这样做,但我真的不确定这种方法,所以如果你能帮助我...

const routes: Routes = [
  { path: 'folders', component : FoldersListComponent},
  {
    path: 'folders/:id/tasks', 
    component : TodoListComponent,
    children: [
      {
        path: 'tasks/:id',
        component: SingleTaskComponent
      }
    ]
  }
];

选项

在这种情况下,嵌套路由涉及更多的代码行。

将此代码块的可读性与您的示例以及我在此 post 底部的第二个代码块进行比较。

  { path: 'folders', component : FoldersListComponent },
  { path: 'folders/:folderId', component : TodoListComponent },
  { path: 'folders/:folderId/tasks/:taskId', component : SingleTaskComponent },

这是一个完美的解决方案。 另请注意,我两次使用了 folderId 和 taskId,而不是 id。这是因为您可能想要访问这些 id,并且记住 ActivatedRoute.snapshot.paramMap.get('id')) 得到了您会有点混乱。


对您的示例的评论

为了完成您的示例,带有子项的路径不能有自己的组件(参考您声明 TodoListComponent 的位置)。您的示例将 folders/3/tasks/tasks/4 像那样路由到 TodoList 组件。

此外,子路径是相对于其父路径的,因此要将任务路径设置为 folders/3/tasks/1/,您只需输入“:id”,如下所示。

  { path: "folders", component: FoldersListComponent },
  {
    path: "folders/:id/tasks",
    children: [
      {
        path: ":id",
        component: SingleTaskComponent,
      },
      {
        path: '',
        pathMatch: 'full',
        component: TodoListComponent,
      }
    ],
  },