掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
Angular Router 支持強大的匹配策略,你可以使用它來幫助用戶在應(yīng)用中導航。該匹配策略支持靜態(tài)路由、帶參數(shù)的可變路由、通配符路由等。此外,還可以為更復雜的 URL 構(gòu)建你自己的自定義模式匹配。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站制作、做網(wǎng)站、寧波網(wǎng)絡(luò)推廣、微信平臺小程序開發(fā)、寧波網(wǎng)絡(luò)營銷、寧波企業(yè)策劃、寧波品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學生創(chuàng)業(yè)者提供寧波建站搭建服務(wù),24小時服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
在本教程中,你將使用 Angular 的 ?UrlMatcher ?來構(gòu)建自定義路由匹配器。此匹配器在 URL 中查找 Twitter ID。
有關(guān)本教程最終版本的工作示例,請參閱現(xiàn)場演練 / 下載范例。
實現(xiàn) Angular 的 ?UrlMatcher ?以創(chuàng)建自定義路由匹配器。
使用 Angular CLI,創(chuàng)建一個新應(yīng)用程序 angular-custom-route-match。除了默認的 Angular 應(yīng)用程序框架之外,還將創(chuàng)建一個 profile 組件。
ng new angular-custom-route-match當提示 ?Would you like to add Angular routing?? 時,選擇 ?Y?。
當系統(tǒng)提示 ?Which stylesheet format would you like to use?? 時,選擇 ?CSS?。
片刻之后,一個新項目 ?angular-custom-route-match? 就準備好了。
angular-custom-route-match? 目錄。ng generate component profileprofile.component.html? 并將其占位內(nèi)容替換為以下 HTML。
Hello {{ username$ | async }}!
app.component.html? 并將其占位內(nèi)容替換為以下 HTML。Routing with Custom Matching
Navigate to my profile
應(yīng)用程序框架就緒后,接下來就要向 ?app.module.ts? 文件中添加路由能力。首先,你要創(chuàng)建一個自定義 URL 匹配器,用于在 URL 中查找 Twitter ID。此 ID 由其前導 ?@? 符號標識出來。
app.module.ts? 文件。RouterModule ?和 ?UrlMatcher ?添加 ?import ?語句。import { RouterModule, UrlSegment } from '@angular/router';imports ?數(shù)組中,添加 ?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
}這個自定義匹配器是一個執(zhí)行以下任務(wù)的函數(shù):
username ?定義為路徑的子字符串。null ?并且路由器繼續(xù)查找與 URL 匹配的其他路由。自定義 URL 匹配器的行為與任何其他路由定義方式是一樣的。請像定義任何其他路由一樣定義子路由或惰性加載路由。
自定義匹配器就位后,你現(xiàn)在需要訂閱 ?profile ?組件中的路由參數(shù)。
profile.component.ts? 文件。ActivatedRoute ?和 ?ParamMap ?添加 ?import ?語句。import { ActivatedRoute, ParamMap } from '@angular/router';map ?添加 ?import ?語句。import { map } from 'rxjs/operators';username ?路由參數(shù)。username$ = this.route.paramMap
.pipe(
map((params: ParamMap) => params.get('username'))
);ActivatedRoute ?注入到組件的構(gòu)造函數(shù)中。constructor(private route: ActivatedRoute) { }代碼就緒后,就可以測試自定義 URL 匹配器了。
ng serve? 命令。ng servehttp://localhost:4200?。你會看到一個網(wǎng)頁,其中包含一個句子,內(nèi)容為 ?Navigate to my profile?。
一個新的句子 ?Hello, Angular!? 出現(xiàn)在頁面上。

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流