# 教程:创建自定义路由匹配器
Angular Router 支持强大的匹配策略,你可以使用它来帮助用户在应用中导航。该匹配策略支持静态路由、带参数的可变路由、通配符路由等。此外,还可以为更复杂的 URL 构建你自己的自定义模式匹配。
在本教程中,你将使用 Angular 的 UrlMatcher来构建自定义路由匹配器。此匹配器在 URL 中查找 Twitter ID。
有关本教程最终版本的工作示例,请参阅现场演练/ 下载范例 。
# 目标
实现 Angular 的 UrlMatcher以创建自定义路由匹配器。
# 前提条件
要完成本教程,你应该对以下概念有基本的了解:
- JavaScript
- HTML
- CSS
- Angular CLI
如果你不熟悉 Angular 路由器的工作原理,请阅读在单页应用程序中使用 Angular 路由。
# 创建一个范例应用
使用 Angular CLI,创建一个新应用程序 angular-custom-route-match。除了默认的 Angular 应用程序框架之外,还将创建一个 profile组件。
- 创建一个新的 Angular 项目 angular-custom-route-match。
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就准备好了。
- 打开终端窗口,进到 - angular-custom-route-match目录。
- 创建一个组件 profile。 
ng generate component profile
- 在你的代码编辑器中,找到文件 profile.component.html并将其占位内容替换为以下 HTML。
src/app/profile/profile.component.html
<p>
Hello {{ username$ | async }}!
</p>
- 在你的代码编辑器中,找到文件 app.component.html并将其占位内容替换为以下 HTML。
src/app/app.component.html
<h2>Routing with Custom Matching</h2>
Navigate to <a router="/@Angular">my profile</a>
<router-outlet></router-outlet>
# 为你的应用程序配置路由
应用程序框架就绪后,接下来就要向 app.module.ts文件中添加路由能力。首先,你要创建一个自定义 URL 匹配器,用于在 URL 中查找 Twitter ID。此 ID 由其前导 @符号标识出来。
- 在你的代码编辑器中,打开 - app.module.ts文件。
- 为 Angular 的 - RouterModule和- UrlMatcher添加- import语句。
src/app/app.module.ts
import { RouterModule, UrlSegment } from '@angular/router';
- 在 imports数组中,添加RouterModule.forRoot([])语句。
src/app/app.module.ts
@NgModule({
  imports:      [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
/* . . . */
    ])],
  declarations: [ AppComponent, ProfileComponent ],
  bootstrap:    [ AppComponent ]
})
- 将如下代码添加到 RouterModule.forRoot()语句中,以便使用自定义路由匹配器。
src/app/app.module.ts
{
  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组件中的路由参数。
- 在你的代码编辑器中,打开 - profile.component.ts文件。
- 为 Angular 的 - ActivatedRoute和- ParamMap添加- import语句。
src/app/profile/profile.component.ts
import { ActivatedRoute, ParamMap } from '@angular/router';
- 为 RxJS 的 map添加import语句。
src/app/profile/profile.component.ts
import { map } from 'rxjs/operators';
- 订阅 username路由参数。
src/app/profile/profile.component.ts
username$ = this.route.paramMap
  .pipe(
    map((params: ParamMap) => params.get('username'))
  );
- 将 ActivatedRoute注入到组件的构造函数中。
src/app/profile/profile.component.ts
constructor(private route: ActivatedRoute) { }
# 测试你的自定义 URL 匹配器
代码就绪后,就可以测试自定义 URL 匹配器了。
- 在终端窗口中,运行 ng serve命令。
ng serve
- 打开浏览器访问 http://localhost:4200。
你会看到一个网页,其中包含一个句子,内容为 Navigate to my profile。
- 单击 my profile超链接。
一个新的句子 Hello, Angular!出现在页面上。
# 下一步
当你的应用程序中有动态 URL 时,使用 Angular Router 提供的模式匹配功能,可以为你提供很大的灵活性。要了解有关 Angular Router 的更多信息,请参阅以下主题:
- 应用内路由和导航
- 路由器 API
此内容基于 Brandon Roberts 的为 Angular Router 使用自定义路由匹配。
