Angular 路由 ( 二 )

Angular 路由 ( 二 )

应用有一个配置过的路由器。 外壳组件中有一个RouterOutlet,它能显示路由器所生成的视图。它还有一些 RouterLink,用户可以点击它们,来通过路由器进行导航。

1. < Base >

大多数带路由的应用都要在index.html<head> 标签下先添加一个 <base> 元素,来告诉路由器该如何 合成导航 用的URL。这样 pushState 才能正常工作。 当引用 CSS 文件、脚本和图片时,浏览器会用 的值作为相对URL 的前缀。

经过ng build命令编译过后,只剩下一个index.html此时,其中就含有<base> 标签。

2. 路由库

路由不是核心部分,需要导入对应的路由模块包,在配置路由信息时导入。

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

3. 配置

使得路由和组件一一对应。即某一个路由要对应显示的组件。app.module.ts 文件下

@NgModule({
  imports: [
    RouterModule.forRoot(
      [
          { path: 'crisis-center', component: CrisisListComponent },
          { path: 'hero/:id',      component: HeroDetailComponent },
          {
            path: 'heroes',
            component: HeroListComponent,
            data: { title: 'Heroes List' }
          },
          { path: '',
            redirectTo: '/heroes',
            pathMatch: 'full'
          },
          { path: '**', component: PageNotFoundComponent }
    ],
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})

hero 路由携带id信息。
heroes 路由的data中携带静态可读数据
redirect 表示重定向,将默认路径‘’重定向到heroes路径下
任意匹配路径,可以匹配404

  1. 先匹配者优先的策略,具体路由应该放在通用路由的前面。
  2. path 不能以斜杠(/)开头

4. 路由占位符

<router-outlet></router-outlet>

5. 导航到占位符

<a routerLink="/heroes" routerLinkActive="active">Heroes</a>

当处于当前页面中时,routerLinkActive发挥作用,给a标签增加 active

6. 路由状态

任意激活路由 开始向上或向下遍历路由树的一种方式,以获得关于 父、子、兄弟路由 的信息。

7. 激活的路由

当前页面显示在路由占位符上面的组件。
可以通过注入 ActivatedRoute 的路由获取url传递的信息。

猜你喜欢

转载自blog.csdn.net/ai_shuyingzhixia/article/details/80470127