angular 2 - 005 路由实现机制

angular2的路由是不是很神奇, url发生了变化却没有看到有任何请求发出?

1. hash模式

url类似 http://localhost:4200/#/task-list,跳转到路由页面再刷新还是会停留在当前路由。这个是我们熟知的路由实现方式, angular1.x用的是这种方式.
开启方法: app.module.ts中引入并provider

import {HashLocationStrategy, LocationStrategy} from '@angular/common';
...
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
...

hashchange - 会添加history记录

当URL的片段标识符更改时,将触发hashchange事件 (跟在#符号后面的URL部分,包括#符号)

2. HTML5 History 模式

angular-cli里默认使用的是HTML5 History 模式,url类似 http://localhost:4200/task-list,URL看着比较舒服,比较美观。在路由页面刷新就会404, 这个需要服务端的配置支持.
现代HTML 5浏览器支持history.pushState API, 这是一项可以改变浏览器的当前地址和历史,却又不会触发服务端页面请求的技术。 太神奇了

Adding and modifying history entries

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. These methods work in conjunction with the window.onpopstate event.

pushState 和 replaceState - 添加和修改history记录

pushState可以改变当前的url却不请求这个页面, 甚至不检查其存在. 这个就是ng2路由的原理 - ng2对每一个路由执行pushState, 这样浏览器的back按钮就能工作了.
注意 pushState() 绝对不会触发 hashchange 事件,即使新的URL与旧的URL仅哈希不同也是如此。

popstate

活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。
需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back())
不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

posted @ 2018-01-03 14:41  CooMark  阅读(1221)  评论(0编辑  收藏  举报