Angular 2路由器不解析子辅助路由

标签 angular typescript modal-dialog router

我正在尝试为模态窗口使用辅助路由。无论我尝试什么,我都无法解决它。我只是收到路由错误。这是我的方法...

app.component.html

<router-outlet></router-outlet>
<router-outlet name="modal"></router-outlet>

admin-routing.module.ts

...
const ROUTES: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    children: [
      {
        path: 'accounts',
        loadChildren: './accounts/accounts.module#AccountsModule'
      },{...}
    ]
  }
];
...

accounts-routing.module.ts

...
const ROUTES: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: AccountsIndexComponent
      },{
        path: 'new',
        component: AccountsNewComponent
      },{
        path: ':id',
        component: AccountsShowComponent
      },{
        path: ':id/edit',
        component: AccountsEditComponent,
        outlet: 'modal'
      }
    ]
  }
];
...

modal.service.ts

  ...
  constructor(
    private router:Router,
    private route:ActivatedRoute
  ) { }
  open(route:Array<any>) {
    this.router.navigate(
      [{outlets: {drawer: route}}], {relativeTo: this.route}
    )
  }
  ...

当我调用 ModalService.open([account.id, 'edit']) 时,它会尝试导航到 /admin/accounts(modal:1/edit) 这是我认为应该做的。但我只是收到一个错误,它无法匹配 1/edit url 段。

NavigationError(id: 2, url: '/admin/accounts(modal:1/edit)', error: Error: Cannot match any routes. URL Segment: '1/edit')

我已经尝试了以下方法,但它们也没有用...

ModalService.open(['accounts', account.id, 'edit'])
ModalService.open(['admin','accounts', account.id, 'edit'])

最佳答案

好像有一个known bug在阻止父路径为空时加载子辅助路由的路由器中,这就是您在 accounts-routing.module.ts 中所做的:

const ROUTES: Routes = [
  {
    path: '',                 // <--- cannot have an empty parent path...
    children: [
      {
         path: ':id/edit',
         component: AccountsEditComponent,
         outlet: 'modal'      // <--- ...with child aux outlet
      }
    ]
  }
]

要解决这个问题,我们必须为路径提供一些东西。例如,如果您将路径命名为 'accounts':

const ROUTES: Routes = [
  {
    path: 'accounts', 
    ...

然后您可以从 routerLink 导航到您的辅助路由:

<a [routerLink]="['accounts', {outlets: {'modal': ['1/edit']}}]">

或以编程方式:

this.router.navigateByUrl('accounts/(modal:1/edit)')

这是一个working Plunkr我弄清楚了这一点并演示了成功加载子辅助路由。

关于Angular 2路由器不解析子辅助路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148272/

相关文章:

css - 带 ionic 2 的 bootstrap-sass

node.js - TypeScript ES6 命名空间

typescript - Typescript接口(interface)声明中命名函数语法的区别

javascript - 在没有 $.ajax() 的 AJAX 上设置超时

AngularJS:关闭模态时的函数调用

当框架不可见时,Java 不处理对话框

Angular 更新 12 至 13 因对等依赖冲突而失败

javascript - Firebase 和 auth 属性在 Ionic 和 Firebase 中不存在

javascript - 无法从 $scope 的事件访问构造函数的上下文

Angular 2 rc.5 : It looks like you're using the old forms module