惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
P
Proofpoint News Feed
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog
U
Unit 42
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
G
Google Developers Blog
I
InfoQ
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
Jina AI
Jina AI
量子位
宝玉的分享
宝玉的分享
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 聂微东
Last Week in AI
Last Week in AI
WordPress大学
WordPress大学
美团技术团队
The Hacker News
The Hacker News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tailwind CSS Blog
博客园 - 司徒正美
博客园 - 叶小钗
Hugging Face - Blog
Hugging Face - Blog
P
Palo Alto Networks Blog
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
博客园 - 【当耐特】
Spread Privacy
Spread Privacy
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
Vercel News
Vercel News
Martin Fowler
Martin Fowler
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Forbes - Security
Forbes - Security
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
P
Privacy International News Feed
G
GRAHAM CLULEY
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
V2EX - 技术
V2EX - 技术

博客园 - Jack Niu

最简单的判断是否为IE浏览器的方法 - document.documentMode “Microsoft.Build.Tasks.Xaml.PartialClassGenerationTask“ task could not be loaded from the assembly ASP.NET Core MVC 入门到精通 - 1. 开发必备工具 (2021) ASP.NET Core MVC 入门到精通 - 3. 使用MediatR 算法 - 计算汉明距离 浏览器(Cache)的缓存逻辑(HTTP条件请求) 算法: 合并两个有序链表 前端进阶(2)使用fetch/axios时, 如何取消http请求 前端进阶(1)Web前端性能优化 2021 Top 100 C#/.NET Interview Questions And Answers 安装umi后,使用umi提示不是内部或者外部命令 解决国内不能访问github的问题 (算法) - 不使用递归,实现斐波那契数列 2021 .NET/dotnet Core/C# 面试题及参考答案 2021 Vue.js 面试题汇总及答案 CSS3 Flex Box 弹性盒子、弹性布局 Angular入门到精通系列教程(15)- 目录结构(工程结构)推荐 Angular入门到精通系列教程(14)- Angular 编译打包 & Docker发布 Angular入门到精通系列教程(13)- 路由守卫(Route Guards) Angular入门到精通系列教程(11)- 模块(NgModule),延迟加载模块
Angular入门到精通系列教程(12)- 路由(Routing)
Jack Niu · 2021-01-25 · via 博客园 - Jack Niu

环境:

  • Angular CLI: 11.0.6
  • Angular: 11.0.7
  • Node: 12.18.3
  • npm : 6.14.6
  • IDE: Visual Studio Code

1. 摘要

简单来说地址栏中,不同的地址(URL)对应不同的页面,这就是路由。同时,点击浏览器的前进和后退按钮,浏览器就会在你的浏览历史中向前或向后导航,这也是基于路由。

在 Angular 里面,Router 是一个独立的模块,定义在 @angular/router 模块中,

  1. Router 可以配合 NgModule 进行模块的延迟加载(懒加载)、预加载操作(参考《Angular入门到精通系列教程(11)- 模块(NgModule),延迟加载模块》);
  2. Router 会管理组件的生命周期,它会负责创建、销毁组件。

对于一个新的基于AngularCLI的项目,初始化时可以通过选项,将AppRoutingModule默认加入到app.component.ts中。

2. 路由(Router)基本用法

2.1. 准备

我们首先创建2个页面,用于说明路由的使用:

ng g c page1
ng g c page2

使用上面AnuglarCLI命令,创建Page1Component, Page2Component 2个组件。

2.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个属性,分别定义路由的相对路径,以及这个路由的响应组件。

2.3. html中的用法

<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中切换

2.4. ts 代码中的用法

有时候,需要根据ts中的业务逻辑,进行跳转。ts中,需要注入Router实例,如

constructor(private router: Router) {}

跳转代码:

  // 跳转到 /page1
  this.router.navigate(['/page1']);

  // 跳转到 /page1/123
  this.router.navigate(['/page1', 123]);

3. 接收参数

3.1. 路径中的参数

一般来说,我们把参数作为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)
  });
}

3.2. 参数(QueryParameter)中的参数

参数还有另外一种写法,如 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)
});

4. URL路径显示格式

不同于传统的纯静态(html)站点,angular中的url不是对应一个真实的文件(页面),因为anuglar接管的路由(Routing)处理,来决定显示那个Component给终端用户。为了针对不同的场景,angular的URL路径显示格式有2中:

  1. http://localhost:4200/page1/123
  2. http://localhost:4200/#/page1/123

默认是第一种,不加#的。如果需要,可以在app-routing.ts中,加入useHash: true, 如:

// app-routing.ts
@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule],
})

5. 部署中遇到的问题

同样,因为anuglar接管的路由(Routing)处理,所以部署时,部署到iis, nginx等等的服务器,都会有不同的技巧(要求),详细参考:
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

6. 总结

  1. angular默认不支持可选路由(e.g. /user/:id?),但是我们可以定义2个路由,指向同一个Component来实现这个,达到代码复用;(或者使用redirectTo)
  2. 可以使用useHash参数,实现augular路径前加一个#;
  3. 读取参数时,都需要subscribe订阅一下,不能直接读取。
  4. 打包后部署问题,查看官方wifi ( https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode

---------------- END ----------------

======================