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

创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于网站制作、做网站、宁波网络推广、微信平台小程序开发、宁波网络营销、宁波企业策划、宁波品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联公司为所有大学生创业者提供宁波建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com
在本教程中,你将使用 Angular 的 UrlMatcher 来构建自定义路由匹配器。此匹配器在 URL 中查找 Twitter ID。
有关本教程最终版本的工作示例,请参阅现场演练 / 下载范例。
实现 Angular 的 UrlMatcher 以创建自定义路由匹配器。
使用 Angular CLI,创建一个新应用程序 angular-custom-route-match。除了默认的 Angular 应用程序框架之外,还将创建一个 profile 组件。
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 目录。ng generate component profileprofile.component.html 并将其占位内容替换为以下 HTML。
Hello {{ username$ | async }}!
app.component.html 并将其占位内容替换为以下 HTML。Routing with Custom Matching
Navigate to my profile
应用程序框架就绪后,接下来就要向 app.module.ts 文件中添加路由能力。首先,你要创建一个自定义 URL 匹配器,用于在 URL 中查找 Twitter ID。此 ID 由其前导 @ 符号标识出来。
app.module.ts 文件。RouterModule 和 UrlMatcher 添加 import 语句。import { RouterModule, UrlSegment } from '@angular/router';imports 数组中,添加 RouterModule.forRoot([]) 语句。@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
/* . . . */
])],
declarations: [ AppComponent, ProfileComponent ],
bootstrap: [ AppComponent ]
})RouterModule.forRoot() 语句中,以便使用自定义路由匹配器。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
}这个自定义匹配器是一个执行以下任务的函数:
username 定义为路径的子字符串。null 并且路由器继续查找与 URL 匹配的其他路由。自定义 URL 匹配器的行为与任何其他路由定义方式是一样的。请像定义任何其他路由一样定义子路由或惰性加载路由。
自定义匹配器就位后,你现在需要订阅 profile 组件中的路由参数。
profile.component.ts 文件。ActivatedRoute 和 ParamMap 添加 import 语句。import { ActivatedRoute, ParamMap } from '@angular/router';map 添加 import 语句。import { map } from 'rxjs/operators';username 路由参数。username$ = this.route.paramMap
.pipe(
map((params: ParamMap) => params.get('username'))
);ActivatedRoute 注入到组件的构造函数中。constructor(private route: ActivatedRoute) { }代码就绪后,就可以测试自定义 URL 匹配器了。
ng serve 命令。ng servehttp://localhost:4200。你会看到一个网页,其中包含一个句子,内容为 Navigate to my profile。
一个新的句子 Hello, Angular! 出现在页面上。