Angular 2 的路由器是一个强大的工具,它允许您在不离开应用程序的情况下导航到不同的视图和组件。在 Angular 2.0.0-rc.1 版本中,路由器已经得到了完全重新设计和改进。在本文中,我们将学习如何使用这个新的路由器。
安装路由器
要使用 Angular 2 的路由器,首先需要安装它。可以通过以下命令安装:
npm install @angular/router@3.0.0-beta.2
配置路由
在 Angular 2 中,路由配置是通过定义一个包含路由信息的数组来完成的。例如:
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
export const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];在这个例子中,我们定义了两个路由:一个是根路由,路径为空,对应的组件是 HomeComponent;另一个是 /about 路由,对应的组件是 AboutComponent。
路由参数
路由还可以带有参数。例如,我们可以定义一个带有 id 参数的路由:
{ path: 'users/:id', component: UserComponent }在这个例子中,id 是一个参数,可以通过路由来传递。例如,访问 /users/123 将会加载 UserComponent 组件,并将 id 参数设置为 123。
子路由
路由还可以嵌套,形成子路由。例如,我们可以定义一个带有子路由的路由:
{ path: 'products', component: ProductsComponent, children: [
{ path: '', component: ProductListComponent },
{ path: ':id', component: ProductDetailComponent }
]}在这个例子中,ProductsComponent 是父组件,包含了两个子路由:空路由对应的是 ProductListComponent 组件,:id 路由对应的是 ProductDetailComponent 组件。
使用路由
一旦配置了路由,我们就可以在组件中使用它。要导航到一个路由,只需要使用 Router 服务的 navigate 方法。例如:
-- -------------------- ---- -------
------ - ------ - ---- ------------------
------ - --------- - ---- ----------------
------------
--------- ---------------
--------- -------- ----------------------- -- ----- --------------
--
------ ----- ----------- -
------------------- ------- ------- --
---------- -
---------------------------------
-
-在这个例子中,当用户点击按钮时,会调用 navigate 方法并导航到 /about 路由。
路由参数
如果路由带有参数,我们可以在导航时传递它们。例如:
navigateToUser(id: number) {
this.router.navigate(['/users', id]);
}在这个例子中,我们传递了 id 参数,导航到 /users/123 路由。
结论
Angular 2 的路由器是一个非常强大和灵活的工具,可以帮助我们构建复杂的应用程序。通过本文的学习,您应该已经掌握了如何使用新的 Angular 2.0.0-rc.1 路由器,并能够在自己的项目中使用它。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/26254