创建一个带路由的项目,依次执行下面每行代码
ng n RouingApp --routing cd RouingApp ng g c components/first ng g c components/second ng g m components/second --routing
代码拷贝:
import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {SecondComponent} from "./second.component"; const routes: Routes = [ { path: '',//默认被异步加载该模块的时候自动引入SecondComponent component: SecondComponent, }, ]; @NgModule({ imports: [RouterModule.forChild(routes)],//注意用于懒加载的模块必须是forChild方式引入 exports: [RouterModule] }) export class SecondRoutingModule { }
代码拷贝:
import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {FirstComponent} from './components/first/first.component'; import {ChildComponent} from './components/first/child/child.component'; import {PageNotFoundComponent} from './components/first/pageNotFound.component'; const routes: Routes = [ { path: '', redirectTo: 'first', pathMatch: 'full' }, { path: 'first', component: FirstComponent,//同步加载 //子路由 children: [ { path: 'child', component: ChildComponent, } ] }, { path: 'second', // loadChildren: './components/second/second.module',//异步加载、惰性加载、懒加载(已失效) loadChildren: () => import('./components/second/second.module').then(m => m.SecondModule),//异步加载、惰性加载、懒加载 }, { path: '**', component: PageNotFoundComponent //当输入路由错误的时候跳转到此页面 } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
把app.component.html代码改成如下
<button routerLink="/">跳转到first</button> <button [routerLink]="['/']">跳转到first</button> <br><br> <button routerLink="/second">跳转到second</button> <button [routerLink]="['/second']">跳转到second</button> <br><br> <router-outlet></router-outlet>
运行项目
ng s --open
访问http://localhost:4200就可以了
💡强哥提示:
如不小心创建错了目录要删除,命令是 rd/s/q 路径/文件夹
如果不小心把app-routing.module.ts或app.module.ts这种路由文件删除了,可以用以下命令:
单独添加app路由文件:ng g m app-routing --flat
单独添加app模块文件:ng g m app --flat
添加app路由以及模块文件:ng g m app --routing --flat