angular——自定义模块 配置路由模块懒加载

当项目比较小的时候可以不用自定义模块,但是当项目非常庞大的时候,可以使用自定义模块来组织项目,并通过 angular 自定义模块实现路由的懒加载

自定义模块

# 创建 user 模块
ng g module modules/user
# 创建 user 模块下的子组件
ng g component modules/user/components/fun
ng g component modules/user/components/news
# 创建 user 模块的组件
ng g component modules/user
  • user 模块 user.module.ts
@NgModule({
  declarations: [NewsComponent, FunComponent, UserComponent],
  // 暴露出自定义模块的组件,未暴露的组件在根模块无法直接使用
  // 但是可以在当前 user 模块使用
  exports: [UserComponent, NewsComponent],
  imports: [
    CommonModule,
  ],
})
  • 使用 user.component.html
<p>
  user works!
</p>
<app-fun></app-fun>
<app-news></app-news>
  • 根模块 app.module.ts
// 引入自定义模块
import { UserModule } from './modules/user/user.module'

imports: [
  UserModule,
],
  • 使用 app.component.html
<app-user></app-user>
<app-news></app-news>
<!--<app-fun></app-fun> 未在模块暴露出去,使用会报错-->

配置路由模块懒加载

# 创建带有路由的模块
ng g module modules/lazy --routing
# 创建 user 模块下的子组件
ng g component modules/lazy/components/bar
ng g component modules/lazy/components/foo
# 创建 user 模块的组件
ng g component modules/lazy
  • 配置路由 password-routing.module.ts
// 引入当前模块的组件
import { LazyComponent } from './lazy.component'

const routes: Routes = [
  { path: '', component: LazyComponent },
]
  • 根模块配置路由 app-routing.module.ts
const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: './modules/lazy/lazy.module#LazyModule',
  },
]
  • 使用 app.component.html
<a routerLink="/lazy">lazy</a>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值