Angular 路由学习记录

76 阅读1分钟

官方教程:angular.cn/guide/route…

我做记录的原因是,我按照自己的理解把学习到的知识点记录下来,方便之后自己查看。

这个练习项目地址:Github

主路由

如果在新建项目时创建路由管理, 当提示 Would you like to add Angular routing? 时,选择 Y。 如果创建项目时没有添加路由管理,后面想添加,可以使用ng命令。
ng generate module app-routing --flat --module=app

然后添加一些页面并配置在app-routing.module.ts

const routes: Routes = [
  //设置重定向 也就是默认展示的组件
  {path: '', redirectTo: '/list', pathMatch: 'full'},
  //一个页面路由
  {path: 'list', component: ListComponent},
  //一个页面路由
  {path: 'details', component: DetaisComponent},
  //home子路由
  {
    path: 'home',
    loadChildren: () => import('./home/home-routing.module').then((x) => x.HomeRoutingModule),
  },
  //通配符路由
  {path: '**', component: PageNotFoundComponent},
];

然后在app.component.html中。

<h1>Angular Router Sample</h1>
<nav>
  <a class="button"
     routerLink="home">
    List
  </a> |
  <a class="button"
     routerLink="/details">
    Details
  </a>
</nav>
<router-outlet></router-outlet>

这样即可实现页面跳转

创建子路由

1. 使用下面命令创建新的module 并创建routing

我这里拿home这个module做示例

ng g module name --routing

2.把新建的module添加到app.module.ts中,例如 HomeModule

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

3.把子module引入 app-routing.module.ts.

例如:

{
  path: 'home',
  loadChildren: () => import('./home/home-routing.module').then((x) => x.HomeRoutingModule),
},

然后即可在新建的路由里面配置子路由或者同级路由。方法看下面的嵌套路由。

嵌套路由

子路由中对子页面注册方式不同,展示的方式也不同。

在子路由的根页面中使用children中注册路由,如下图:

image.png

然后再home-component.html 中使用 router-outlet

image.png

details 和 orderPay 将在 home页面中展示出来。也就属于home的子页面。

但是如果和home 放平级,如下图:

image.png

details 和 orderPay, 将会在 父(上级)路由中,根页面的 router-outlet中展示出来。也就是和home同级。