Angular 6:无法在页面加载时加载子路由

时间:2018-08-31 09:47:40

标签: angular angular6 angular-routing

例如在功能模块路线上重新加载页面时出现问题;我可以导航到

http://example.com/#/dashboard

但是如果我随后在浏览器中强制刷新页面,则会出现以下导航错误:

Router Event: NavigationError
platform-browser.js:211 NavigationError(id: 1, url: '/dashboard', 
error: TypeError: undefined is not a function)
platform-browser.js:211 NavigationError {id: 1, url: "/dashboard", 
error: TypeError: undefined is not a function
at Array.map (<anonymous>)
at webpackAsyncContext (ht…}

我的路由文件内容如下:

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes, CanActivateChild } from '@angular/router';

const routes: Routes = [
    {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardModule'
    },
    { 
        path: '',
        redirectTo: '',
        pathMatch: 'full'
    }
];

@NgModule({
  imports: [

    RouterModule.forRoot(routes, { enableTracing: true, useHash: true } )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

dashboard-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent } from './dashboard.component';

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

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

dashboard.module.ts:

import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'

import { SharedModule } from '../shared/shared.module'

import { DashboardRoutingModule } from './dashboard-routing.module'
import { DashboardComponent } from './dashboard.component'

@NgModule({
    imports: [
        CommonModule,
        DashboardRoutingModule,
        SharedModule
    ],
    declarations: [
        DashboardComponent
    ],
    exports: [
        DashboardRoutingModule
    ]
})
export class DashboardModule { }

app.module.ts:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'

import { CoreModule } from './core/core.module'
import { SharedModule } from './shared/shared.module'

import { DashboardModule } from './dashboard/dashboard.module'
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { DashboardComponent } from './dashboard/dashboard.component'

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CoreModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    CoreModule.forRoot(),
    DashboardModule,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

1 个答案:

答案 0 :(得分:1)

如果您正在使用延迟加载,则不得将延迟加载的模块包含在导入中(也不能从该模块使用TS导入),因为它将随导入模块一起加载。

planet_hunter在这里为发现您的进口商品大功告成。