Angular Router 将 URL 路径映射到组件,在单页应用中启用导航而无需完整页面重新加载。您定义一个路由配置数组,将路径链接到组件。
定义路由
ts
{ } ;
: = [
{ : , : },
{ : , : },
{ : , : },
{ : , : ().( m.) },
{ : , : },
];
<!-- the router renders the matched component here -->
<router-outlet></router-outlet>
<a routerLink="/users" routerLinkActive="active">Users</a>
<a [routerLink]="['/users', user.id]">View {{ user.name }}</a> <!-- dynamic path -->
routerLink 执行客户端导航(无需重新加载),routerLinkActive 在链接的路由处于活跃状态时添加 CSS 类——对导航高亮很有用。
import { Router } from "@angular/router";
export class LoginComponent {
constructor(private router: Router) {}
onLogin() {
this.router.navigate(["/dashboard"]); // navigate after an action
}
}
import { ActivatedRoute } from "@angular/router";
export class UserDetailComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// read :id from the URL (params is an Observable, since it can change)
this.route.params.subscribe(p => this.userId = p["id"]);
// or snapshot for a one-time read:
const id = this.route.snapshot.paramMap.get("id");
}
}
Nested/child routes, route guards (auth), resolvers (pre-fetch data),
query params, and lazy loading of feature routes for code splitting.
Router 就是将 Angular 转变为多视图 SPA 的东西——快速的客户端导航、URL 驱动的 UI 和可深度链接的页面。
了解路由配置、<router-outlet>、routerLink 与编程式 Router.navigate 的区别,以及通过 ActivatedRoute 读取参数,涵盖了任何 Angular 应用的日常路由需求,而守卫和延迟加载在此基础上进一步扩展。