简体   繁体   中英

Angular 6 Lazy loading route

I wanted to add lazy loaded route for admin in my project. I'm using ASP Net Core backend and Angular 6 frontend, so my output dir for compile code is: wwwRoot/Angular/dist. When I compiled project, I see that file "admin-admin-module-ngfactory.js exists there, but when I try to enter page '/admin/dash', it throw error:

Failed to load resource: the server responded with a status of 404 (Not Found)
Error: Uncaught (in promise): Error: Loading chunk admin-admin-module-ngfactory failed.
(error: http://localhost:5000/admin-admin-module-ngfactory.js)
Error: Loading chunk admin-admin-module-ngfactory failed.
(error: http://localhost:5000/admin-admin-module-ngfactory.js)

Here is my routing modules:

admin-routing.module.ts:

const routes: Routes = [ 
  { path: 'dash', component: AdminDashboardComponent, pathMatch: 'full'}
];


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

and app-routing.module.ts:

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'error', component: ErrorComponent },
  { path: 'admin', loadChildren: './admin/admin.module#AdminModule' },
  { path: '', pathMatch: 'full', redirectTo: 'dashboard' },
];

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

UPDATE:

If I run project with dotnet run (with ng build --aot) it doesn't work, but if I launch only Angular app with ng serve --aot it works.

Add below line in .angular-cli.json file.

"apps": [
{
  "deployUrl": "Angular-Build-Path/",

Thanks.

According deploy documentation of Angular:

If you copy the files into a server sub-folder, append the build flag, --base-href and set the appropriately.

So, you should use the --base-href parameter in .angular-cli.json file.

Optionally, you can work in development mode without -base-href configuration(in the angular-cli- file) and only set it at aplication production build.

ng build --base-href=/Angular/dist/

References:

https://angular.io/guide/deployment#simplest-deployment-possible

https://angular.io/guide/deployment#the-base-tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM