





























环境:
- Angular CLI: 11.0.6
- Angular: 11.0.7
- Node: 12.18.3
- npm : 6.14.6
- IDE: Visual Studio Code
简单来说地址栏中,不同的地址(URL)对应不同的页面,这就是路由。同时,点击浏览器的前进和后退按钮,浏览器就会在你的浏览历史中向前或向后导航,这也是基于路由。
在 Angular 里面,Router 是一个独立的模块,定义在 @angular/router 模块中,
对于一个新的基于AngularCLI的项目,初始化时可以通过选项,将AppRoutingModule默认加入到app.component.ts中。
我们首先创建2个页面,用于说明路由的使用:
ng g c page1
ng g c page2
使用上面AnuglarCLI命令,创建Page1Component, Page2Component 2个组件。
//src\app\app-routing.module.ts
const routes: Routes = [
{
path: 'page1',
component: Page1Component
},
{
path: 'page2',
component: Page2Component
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
可以看到,简单的路由注册,只需要path和component2个属性,分别定义路由的相对路径,以及这个路由的响应组件。
<a routerLink="page1">Page1</a> |
<a routerLink="page2">Page2</a>
在html模板中,直接使用routerLink属性,标识为angular的路由。执行代码,可以看到 Page1和Page2 两个超链接,点击可以看到地址栏地址改为http://localhost:4200/page2或 http://localhost:4200/page1 , 页面内容在page1和page2中切换
有时候,需要根据ts中的业务逻辑,进行跳转。ts中,需要注入Router实例,如
constructor(private router: Router) {}
跳转代码:
// 跳转到 /page1
this.router.navigate(['/page1']);
// 跳转到 /page1/123
this.router.navigate(['/page1', 123]);
一般来说,我们把参数作为url中的一段,如/users/1, 代表查询id是1的用户,路由定义为"/users/id" 这种风格。
针对我们的简单页面,比如我们的page1页面可以传id参数,那么我们需要修改我们的routing为:
const routes: Routes = [
{
path: 'page1/:id', //接收id参数
component: Page1Component,
},
{
// 实现可选参数的小技巧。 这个routing处理没有参数的url
path: 'page1',
redirectTo: 'page1/', // 跳转到'page1/:id'
},
{
path: 'page2',
component: Page2Component,
},
];
ts代码读取参数时, 首先需要注入ActivatedRoute,代码如下:
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit(): void {
this.activatedRoute.paramMap.subscribe((params) => {
console.log('Parameter id: ', params.get('id'));
// 地址 http://localhost:4200/page1/33
// 控制台输出:Query Parameter name: 33
// 地址 http://localhost:4200/page1/
// 控制台输出:Query Parameter name: (实际结果为undefined)
});
}
参数还有另外一种写法,如 http://localhost:4200/?name=cat , 即URL地址后,加一个问号'?', 之后再加参数名和参数值('name=cat')。这种称为查询参数(QueryParameter)。
取这查询参数时,和之前的路由参数类似,只是paramMap改为queryParamMap,代码如下:
this.activatedRoute.queryParamMap.subscribe((params) => {
console.log('Query Parameter name: ', params.get('name'));
// 地址 http://localhost:4200/page1?name=cat
// 控制台输出:Query Parameter name: cat
// 地址 http://localhost:4200/page1/
// 控制台输出:Query Parameter name: (实际结果为undefined)
});
不同于传统的纯静态(html)站点,angular中的url不是对应一个真实的文件(页面),因为anuglar接管的路由(Routing)处理,来决定显示那个Component给终端用户。为了针对不同的场景,angular的URL路径显示格式有2中:
默认是第一种,不加#的。如果需要,可以在app-routing.ts中,加入useHash: true, 如:
// app-routing.ts
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule],
})
同样,因为anuglar接管的路由(Routing)处理,所以部署时,部署到iis, nginx等等的服务器,都会有不同的技巧(要求),详细参考:
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
---------------- END ----------------
======================
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。