导入模块中的 Angular 2 路由覆盖当前 [英] Angular 2 routes in imported module override current

查看:27
本文介绍了导入模块中的 Angular 2 路由覆盖当前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 plunker:https://plnkr.co/edit/WIFNVIEVqls4gXk21Muj

Here's the plunker: https://plnkr.co/edit/WIFNVIEVqls4gXk21Muj

有 2 个模块都定义了路由.模块 2 导入模块 1 以使用其中的组件.您永远无法导航到模块 2.而是加载模块 1.

There're 2 modules both have routes defined. Module 2 imports module 1 in order to use a component from it. You can never navigate to Module 2. Module 1 loads instead.

模块 1 路由:

const routes: Routes = [
  { path: '', component: Module1Component }
];

模块 2 路由:

const routes: Routes = [
  { path: '', component: Module2Component }
];

应用路由:

const routes: Routes = [
  { path: 'module1', loadChildren: 'app/module1/module1.module#Module1Module' },
  { path: 'module2', loadChildren: 'app/module2/module2.module#Module2Module' }
];

谢谢.

推荐答案

有两个问题可以解决这个问题.首先,路由器存在一个错误,它考虑了导入模块的顺序.有关错误的更多详细信息,请参阅此错误报告:https://github.com/angular/angular/issues/12648

Two issues to get this working. First, there is a bug with the router that takes in account the order of your imported modules. For more details on the error, see this bug report: https://github.com/angular/angular/issues/12648

所以为了解决这个问题,你需要改变你在 module2.module.ts 中的导入顺序,以便你的 module2 路由文件在你导入 module1 之前被导入.

So to get around the bug, you need to change the order of your imports in module2.module.ts so that your module2 routing file is imported before you import module1.

@NgModule({
    imports: [
        routing, // this order is important
        Module1Module
    ],
    declarations: [
        Module2Component
    ]
})

第二,不要使用 ModuleWithProviders 将路由模块导出为常量,而是将其导出为类.也就是更改 module2 路由文件 (module2.routing.ts) 以导出这样的类(您需要导入 NgModule):

Second, instead of exporting your routing module as a const using ModuleWithProviders export it as a class. aka change the module2 routing file (module2.routing.ts) to export a class like so (you'll need to import NgModule):

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class routing {
}

这应该会为您解决.这是一个工作 plunker:https://plnkr.co/edit/5impstull9EBCUxlw26k

This should fix it for you. Here's a working plunker: https://plnkr.co/edit/5impstull9EBCUxlw26k

这篇关于导入模块中的 Angular 2 路由覆盖当前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆