路由器导航到子路线-Angular 6

Ant*_*reš 5 angular angular-router angular6 angular-routerlink

我已经定义了这样的路线:

const routes: Routes = [
    { path: '', loadChildren: './tabs/tabs.module#TabsPageModule' },
    { path: 'faq', loadChildren: './faq/faq.module#FaqPageModule' },
    { path: 'terms', loadChildren: './terms/terms.module#TermsPageModule' }
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}
Run Code Online (Sandbox Code Playgroud)

像这样:

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: '/tabs/(list:list)',
        pathMatch: 'full',
      },
      {
        path: 'list',
        outlet: 'list',
        component: ListPage
      },
      {
        path: 'profile',
        outlet: 'profile',
        component: ProfilePage,
        canActivate: [AuthGuardService]
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/(list:list)',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}
Run Code Online (Sandbox Code Playgroud)

我对如何使用.navigate()组件或routerLink某些html元素中的路由器方法导航到ListPage或ProfilePage感兴趣。

我尝试过这样的事情

this.router.navigate(['tabs/profile']);
Run Code Online (Sandbox Code Playgroud)

要么

this.router.navigate(['profile']);
Run Code Online (Sandbox Code Playgroud)

要么

this.router.navigate(['tabs(profile:profile)']);
Run Code Online (Sandbox Code Playgroud)

并得到此错误:

错误:无法匹配任何路线。网址区隔:”

小智 11

this.router.navigate(['/list'], {relativeTo: this.route});      //absolute
this.router.navigate(['./list'], {relativeTo: this.route});     //child
this.router.navigate(['../list'], {relativeTo: this.route});    //sibling
this.router.navigate(['../../list'], {relativeTo: this.route}); //parent
this.router.navigate(['tabs/list'], {relativeTo: this.route});
this.router.navigate(['/tabs/list'], {relativeTo: this.route});
Run Code Online (Sandbox Code Playgroud)

你会在这里找到更多信息

  • 欢迎来到 stackoverflow。除了您提供的答案之外,请考虑提供简要说明,说明原因以及如何解决该问题。 (3认同)

小智 8

尝试:

this.router.navigate(['child component path'], {relativeTo: this.activatedRoute});
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题。快乐的编码:)

  • 不要忘记添加 `import { ActivatedRoute } from '@angular/router';` (3认同)

Rah*_*hul 5

如果要导航到该list路线,则需要使角度知道其为tabs

this.router.navigate(['/tabs/list']); 要么 this.router.navigate(['tabs','list']);

在路由器导航中,您需要将路由作为数组传递,string因此,现在角度将找到父tabs路径并检查子路径是否为空,pathMatch: 'full'否则将导航到特定子路径

在routerLink你可以使用相同的阵列相匹配的路由

谢谢,祝您编程愉快!


Ant*_*reš 2

我通过在“”和“选项卡”路径下方添加配置文件路径找到了解决方案:

  {
    path: 'profile',
    redirectTo: '/tabs/(profile:profile)',
    pathMatch: 'full'
  }
Run Code Online (Sandbox Code Playgroud)

现在我可以导航到个人资料

  this.router.navigate(['profile']);
Run Code Online (Sandbox Code Playgroud)

我忘记在 tabs.router.module.ts 中添加此路径。因此我被提到了错误