在Angular v17 CLI中,默认为独立模式,不再需要使用@NgModule
进行路由配置。新的解决方法是使用路由模块进行延迟加载。
下面是一个示例代码,演示如何使用路由模块进行延迟加载:
首先,在根目录下创建一个名为app-routing.module.ts
的路由模块文件,内容如下:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
{ path: 'about', loadChildren: () => import('./about/about.module').then(m => m.AboutModule) },
// 其他路由配置
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
然后,在根模块文件app.module.ts
中引入并使用AppRoutingModule
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule // 引入路由模块
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
接下来,创建一个名为home.module.ts
的懒加载模块文件,内容如下:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home.component';
import { HomeRoutingModule } from './home-routing.module';
@NgModule({
declarations: [
HomeComponent
],
imports: [
CommonModule,
HomeRoutingModule // 引入子模块的路由模块
]
})
export class HomeModule { }
然后,在home
目录下创建一个名为home-routing.module.ts
的子模块路由文件,内容如下:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
最后,创建一个名为home.component.ts
的组件文件,内容如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `Home Component
`,
})
export class HomeComponent { }
通过以上步骤,你就可以在Angular v17 CLI中实现延迟加载并配置路由了。同样的方法也适用于其他需要延迟加载的路由模块。
上一篇:Angular v16和Akita出现错误:类型错误:this.userQuery.select不是一个函数。
下一篇:Angular V17-SSR-ERROR 错误:NullInjectorError:没有为WrappedSocket提供者。