2

我正在使用 Angular 路由来浏览组件。当用户登录时,他们被导航到dashboard/:id然后他们看到dashboard/123/projects等等。问题是,当用户/dashboard仅导航到时,我想/dashboard/:id默认将它们重定向到。但是当我这样做时:{ path:"dashboard", redirectTo:"dashboard/:id/projects", pathMatch:"full"}它通过一个错误说:id未定义,并且我无法导航到从/dashboard当前用户登录/dashboard/123/projects

我的 Routes.modules.ts 代码

const routes: Routes = [{
    path: "",
    redirectTo: "/login",
    pathMatch: "full"
  },
  {
    path: "login",
    component: LoginComponent
  },
  {
    path: "register",
    component: RegisterComponent
  },
  //the problem goes here
  {
    path: "dashboard",
    redirectTo: "", //How to redirect to dashboard/:id ?
    pathMatch: "full"
  },
  {
    path: "dashboard/:id",
    component: DashboardComponent,
    children: [{
        path: "",
        redirectTo: "projects",
        pathMatch: "full"
      },
      {
        path: "projects",
        component: ProjectsComponent
      },
      {
        path: "archived",
        component: ArchivedProjectsComponent
      },
      {
        path: "projects/:id",
        component: SingleProjectComponent,
        children: [{
            path: "",
            redirectTo: "plans",
            pathMatch: "full"
          },
          {
            path: "plans",
            component: PlansComponent
          },
          {
            path: "tasks",
            component: TasksComponent
          },
          {
            path: "photos",
            component: PhotosComponent
          },
          {
            path: "files",
            component: FilesComponent
          },
          {
            path: "people",
            component: PeopleComponent
          },
          {
            path: "settings",
            component: SettingsComponent
          },
          {
            path: "trash",
            component: TrashComponent
          },
          {
            path: "**",
            redirectTo: "plans",
            pathMatch: "full"
          }
        ]
      },
      {
        path: "**",
        redirectTo: "projects",
        pathMatch: "full"
      }
    ]
  },
  {
    path: "**",
    component: PageNotFoundComponent
  },
];

4

2 回答 2

3

您可以使用 Login 组件来实现这一点。成功登录后将用户重定向到子路由。

从有效负载或您的 API 调用中获取用户的 id 取决于您的结构,并将其传递给路由。

this.router.navigate(['/dashboard/' + id + '/projects']);

this.router是 的一个实例Router

于 2019-05-15T12:21:26.937 回答
1

我认为您需要将“:id”的值存储在请求之间的本地存储中,即。存储最后一个“id”。

在您的重定向中提供一个任意值,然后在您的DashboardComponent. 查找 9999(或其他),然后替换本地存储中的值。

  ngOnInit() {
localStorage.getItem('id'))
  }
{
    path: "dashboard",
    redirectTo: "dashboard/99999", //How to redirect to dashboard/:id ?
    pathMatch: "full"
  }
于 2019-05-15T12:25:07.953 回答