创建
1 在ng new xxx时,可以选择路由模块
2 通过 ng new routing-app --routing --defaults创建带有路由的应用 如下所示
基本配置
自定义路由的配置
routing-moudle模块
import { NgModule } from '@angular/core';
import { RouterModule, Routes, UrlSegment } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
const routes: Routes = [
{
matcher: (url) => {
if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
return {
consumed: url,
posParams: {
username: new UrlSegment(url[0].path.substr(1), {})
}
};
}
return null;
},
component: ProfileComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
组件
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css'],
})
export class ProfileComponent implements OnInit {
username$ = this.route.paramMap.pipe(
map((params: ParamMap) => params.get('username'))
);
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {}
}
组件的html
<p>Hello {{username$ | async}}</p>