Angular 2路由器,错误:无法激活已激活的插座

问题描述 投票:6回答:2

我想我根本无法理解Angular 2路由。我在我的应用程序中有这个结构:

const routes: Routes = [
    {
        path: 'login',
        component: LoginViewComponent
    },
    {
        path: 'main',
        component: MainComponent,
        children:
        [
            {
                path: 'unit_list',
                component: ListViewComponent
            },
            {
                path: 'unit_info',
                component: UnitInfoComponent,
                children:
                [
                    {
                        path: 'patient',
                        component: PatientDetailsComponent
                    }
                ]
            }
        ]
    },
    {
        path: '',
        redirectTo: 'main',
        pathMatch: 'full'
    }
];

以下是我的app.module的样子:

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        MainModule,
        routing
    ],
    declarations: [
        AppComponent,
        LoginViewComponent
    ],
    bootstrap: [AppComponent]
})

和main.module

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        RouterModule
    ],
    declarations: [
        ListViewComponent,
        MainComponent,
        PatientDetailsComponent,
        UnitInfoComponent,
    ]
})

问题是我无法管理让router.navigateByUrl函数工作。

我在PatientDetailsComponent中有ngOnInit()函数,它检查患者是否为null,如果是,那么我称之为“this.router.navigateByUrl(”/ main / unit_info“)”,但它会在标题中抛出错误:“无法激活一个已经激活的插座“。它在Angular 2.1.1中运行良好,但是当我升级到2.4.X时似乎没有解决我的问题。我也不确定这条路由是否正确,因为我有点迷路。

这是我整个路由在升级到2.4.X之前的样子:http://pastebin.com/Y377STcW

angular
2个回答
4
投票

这个错误可能是一个令人讨厌的红鲱鱼!

你会在Chrome控制台中看到类似的内容:

 core.js:1440 ERROR Error: Uncaught (in promise): Error: Cannot
 activate an already activated outlet Error: Cannot activate an already
 activated outlet
     at RouterOutlet.activateWith (router.js:6676)
     at ActivateRoutes.activateRoutes (router.js:5765)
     at eval (router.js:5705)
     at Array.forEach (<anonymous>)
     at ActivateRoutes.activateChildRoutes (router.js:5704)

你会去检查你的路线和你的提供者和你的HTML,你不会发现任何错误。

然后突然间你会发生!

然后您将在控制台窗口中向上滚动。你会看到从屏幕顶部推出的真正错误:

core.js:1440 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'foo' of null
TypeError: Cannot read property 'foo' of null

然后查找与您的组件对应的.ts文件,单击它,它将带您直接返回代码行并显示错误。

换句话说,路由器无法承受构建组件期间发生的错误。 ngInit方法可能有不同的结果 - 尚未测试。在任何一种情况下,路由都很好:-)


0
投票

请查看https://angular.io/docs/ts/latest/guide/router.html#!#child-routing-component的类似示例。

我认为你应该使用RouterModule.forChild(routes)并在你的一个@NgModule中添加下面的行

exports: [
    RouterModule
]
© www.soinside.com 2019 - 2024. All rights reserved.