在开发单页面应用(SPA)时,路由是必不可少的组成部分。Angular 2 提供了强大的路由功能,可以帮助开发者轻松实现页面跳转和组件加载。本文将详细解析 Angular 2 路由的设置,帮助新手快速入门实战配置。
一、Angular 2 路由基础
1. 路由模块
在 Angular 2 中,首先需要引入 @angular/router 模块。在 app.module.ts 文件中,导入 RouterModule 并将其添加到 declarations 和 imports 数组中。
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [
// ...
],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// ...
])
],
// ...
})
export class AppModule { }
2. 路由配置
在上面的代码中,我们使用了 RouterModule.forRoot() 方法来配置路由。该方法接收一个路由数组,每个路由对象包含以下属性:
path:路由的路径,用于匹配 URL。component:当路由匹配成功时,要加载的组件。pathMatch:匹配模式,可选值为'full'或'prefix'。'full'表示完全匹配,'prefix'表示匹配路径的前缀。
3. 路由组件
在 Angular 2 中,每个路由都对应一个组件。组件可以是自定义组件,也可以是 Angular 内置组件。例如,以下代码定义了一个名为 HomeComponent 的自定义组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `
<h1>首页</h1>
`
})
export class HomeComponent { }
二、路由导航
1. 组件内部导航
在组件内部,可以使用 Router 服务进行导航。以下代码演示了如何从 HomeComponent 跳转到 AboutComponent:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
template: `
<button (click)="goToAbout()">跳转到关于页面</button>
`
})
export class HomeComponent {
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['about']);
}
}
2. 路由参数
在路由配置中,可以使用冒号 : 来定义参数。以下代码演示了如何传递参数:
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
RouterModule.forRoot([
{ path: 'user/:id', component: UserComponent }
])
],
// ...
})
export class AppModule { }
在组件内部,可以使用 ActivatedRoute 服务获取参数:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user',
template: `
<h1>用户信息</h1>
<p>用户 ID:{{ userId }}</p>
`
})
export class UserComponent implements OnInit {
userId: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.userId = params['id'];
});
}
}
三、路由守卫
路由守卫可以用来控制路由访问权限。以下代码演示了如何使用路由守卫:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate() {
if (this.isAuthenticated()) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
}
isAuthenticated(): boolean {
// 判断用户是否登录
return false;
}
}
在路由配置中,将 AuthGuard 添加到 canActivate 数组中:
import { RouterModule } from '@angular/router';
import { AuthGuard } from './auth-guard';
@NgModule({
imports: [
RouterModule.forRoot([
{ path: 'user/:id', component: UserComponent, canActivate: [AuthGuard] }
])
],
// ...
})
export class AppModule { }
四、总结
本文详细解析了 Angular 2 路由的设置,包括路由模块、路由配置、路由导航、路由参数和路由守卫。通过本文的学习,相信你已经对 Angular 2 路由有了更深入的了解。在实际开发中,灵活运用路由功能,可以帮助你轻松实现页面跳转和组件加载。
