Angular 教程:创建自定义路由匹配器

2022-07-04 10:10 更新

教程:创建自定义路由匹配器

Angular Router 支持强大的匹配策略,你可以使用它来帮助用户在应用中导航。该匹配策略支持静态路由、带参数的可变路由、通配符路由等。此外,还可以为更复杂的 URL 构建你自己的自定义模式匹配。

在本教程中,你将使用 Angular 的 ​UrlMatcher ​来构建自定义路由匹配器。此匹配器在 URL 中查找 Twitter ID。

有关本教程最终版本的工作示例,请参阅现场演练 / 下载范例

目标

实现 Angular 的 ​UrlMatcher ​以创建自定义路由匹配器。

创建一个范例应用

使用 Angular CLI,创建一个新应用程序 angular-custom-route-match。除了默认的 Angular 应用程序框架之外,还将创建一个 profile 组件。

  1. 创建一个新的 Angular 项目 angular-custom-route-match
  2. ng new angular-custom-route-match

    当提示 ​Would you like to add Angular routing?​ 时,选择 ​Y​。

    当系统提示 ​Which stylesheet format would you like to use?​ 时,选择 ​CSS​。

    片刻之后,一个新项目 ​angular-custom-route-match​ 就准备好了。

  3. 打开终端窗口,进到 ​angular-custom-route-match​ 目录。
  4. 创建一个组件 profile
  5. ng generate component profile
  6. 在你的代码编辑器中,找到文件 ​profile.component.html​ 并将其占位内容替换为以下 HTML。
  7. <p>
    Hello {{ username$ | async }}!
    </p>
  8. 在你的代码编辑器中,找到文件 ​app.component.html​ 并将其占位内容替换为以下 HTML。
  9. <h2>Routing with Custom Matching</h2>
    
    Navigate to <a routerLink="/@Angular">my profile</a>
    
    <router-outlet></router-outlet>

为你的应用程序配置路由

应用程序框架就绪后,接下来就要向 ​app.module.ts​ 文件中添加路由能力。首先,你要创建一个自定义 URL 匹配器,用于在 URL 中查找 Twitter ID。此 ID 由其前导 ​@​ 符号标识出来。

  1. 在你的代码编辑器中,打开 ​app.module.ts​ 文件。
  2. 为 Angular 的 ​RouterModule ​和 ​UrlMatcher ​添加 ​import ​语句。
  3. import { RouterModule, UrlSegment } from '@angular/router';
  4. 在 ​imports ​数组中,添加 ​RouterModule.forRoot([])​ 语句。
  5. @NgModule({
      imports:      [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot([
          {
    /* . . . */
        ])],
      declarations: [ AppComponent, ProfileComponent ],
      bootstrap:    [ AppComponent ]
    })
  6. 将如下代码添加到 ​RouterModule.forRoot()​ 语句中,以便使用自定义路由匹配器。
  7. matcher: (url) => {
        if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
          return {
            consumed: url,
            posParams: {
              username: new UrlSegment(url[0].path.slice(1), {})
            }
          };
        }
    
        return null;
      },
      component: ProfileComponent
    }

这个自定义匹配器是一个执行以下任务的函数:

  • 匹配器验证数组是否只包含一个区段。
  • 匹配器使用正则表达式来确保用户名的格式是匹配的。
  • 如果匹配,则该函数返回整个 URL,将路由参数 ​username ​定义为路径的子字符串。
  • 如果不匹配,则该函数返回 ​null ​并且路由器继续查找与 URL 匹配的其他路由。

自定义 URL 匹配器的行为与任何其他路由定义方式是一样的。请像定义任何其他路由一样定义子路由或惰性加载路由。

订阅路由参数

自定义匹配器就位后,你现在需要订阅 ​profile ​组件中的路由参数。

  1. 在你的代码编辑器中,打开 ​profile.component.ts​ 文件。
  2. 为 Angular 的 ​ActivatedRoute ​和 ​ParamMap ​添加 ​import ​语句。
  3. import { ActivatedRoute, ParamMap } from '@angular/router';
  4. 为 RxJS 的 ​map ​添加 ​import ​语句。
  5. import { map } from 'rxjs/operators';
  6. 订阅 ​username ​路由参数。
  7. username$ = this.route.paramMap
      .pipe(
        map((params: ParamMap) => params.get('username'))
      );
  8. 将 ​ActivatedRoute ​注入到组件的构造函数中。
  9. constructor(private route: ActivatedRoute) { }

测试你的自定义 URL 匹配器

代码就绪后,就可以测试自定义 URL 匹配器了。

  1. 在终端窗口中,运行 ​ng serve​ 命令。
  2. ng serve
  3. 打开浏览器访问 ​http://localhost:4200​。
  4. 你会看到一个网页,其中包含一个句子,内容为 ​Navigate to my profile​。

  5. 单击 my profile 超链接。
  6. 一个新的句子 ​Hello, Angular!​ 出现在页面上。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号