Angular7添加路由及子路由方法

官方文档:
https://angular.io/guide/lazy-loading-ngmodules
关键词:路由、懒加载、特性模块

在angular5以上版本官方给的方法是新建两个带路由的模块,再在模块中添加组件,这样根路由包括这两个模块,各自模块又能找到路由,代码如下:

ng new customer --routing
ng generate module customers –routing
ng generate component customers/customer-list
ng generate module orders –routing
ng generate component orders/order-list

根页面HTML代码:

<button routerLink="/customers">Customers</button>
<button routerLink="/orders">Orders</button>
<button routerLink="">Home</button>

<router-outlet></router-outlet>

找到各自模块需要在根路由中设置,注意loadChildren:
src/app/app-routing.module.ts

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: './customers/customers.module#CustomersModule'
  },
  {
    path: 'orders',
    loadChildren: './orders/orders.module#OrdersModule'
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

各自特性模块基本在创建组件时会import组件名称,基本不用管,只需在该模块的路由中添加子组件的路由:
src/app/customers/customers-routing.module.ts:

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

import { CustomerListComponent } from './customer-list/customer-list.component';


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

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

注意:path后是空格

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值