Angular路由复用策略
一、引言路由在执行过程中对组件无状态操作,即路由离退时组件状态也一并被删除;当然在绝大多数场景下这是合理的。 但有时一些特殊需求会让人半死亡状态,当然这一切都是为了用户体验;一种非常常见场景,在移动端中用户通过关键词搜索商品,而死不死的这样的列表通常都会是自动下一页动作,此时用户好不容易滚动到第二页并找到想要看的商品时,路由至商品详情页,然后一个后退……用户懵逼了。 Angular路由与组件一开始就透过 而每一个路由并不一定是一次性消费,Angular 利用
二、RouteReuseStrategy
这看起来就像是一个时间轴关系,用一种白话文像是这样:把路由 当理解这一原理时,假如我们拿开头搜索列表返回的问题就变得非常容易解决。 三、一个示例诚如上面说明的,只需要实现 1、创建策略import {RouteReuseStrategy,DefaultUrlSerializer,ActivatedRouteSnapshot,DetachedRouteHandle} from '@angular/router'; export class SimpleReuseStrategy implements RouteReuseStrategy { _cacheRouters: { [key: string]: any } = {}; shouldDetach(route: ActivatedRouteSnapshot): boolean { return true; } store(route: ActivatedRouteSnapshot,handle: DetachedRouteHandle): void { this._cacheRouters[route.routeConfig.path] = { snapshot: route,handle: handle }; } shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!this._cacheRouters[route.routeConfig.path]; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return this._cacheRouters[route.routeConfig.path].handle; } shouldReuseRoute(future: ActivatedRouteSnapshot,curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } 定义一个
2、注册最后将策略注册到模块当中: providers: [ { provide: RouteReuseStrategy,useClass: SimpleReuseStrategy } ] 假设我们有这么一个路由配置: RouterModule.forRoot([ { path: 'search',component: SearchComponent },{ path: 'edit/:id',component: EditComponent } ]) 搜索组件用于搜索动作,并在根据搜索结果跳转至编辑页,保存后又回到最后搜索结果的状态(这部分代码我就不贴有兴趣见 plnkr)。 四、结论上述只是一个简单的抛砖引玉作用,实则对于复用的判断会更复杂、滚动条位置、缓存清理等等。 善用这种路由复用策略机制可以解决很多Web体验上的问题。 Happy coding! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Angular 4/5 – 路线paramMap vs params
- bootstrap-datetimepicker:基于twitter bootstrap的日期/时
- 8天入门docker系列 —— 第二天 通过一个aspnetcore程序加深
- 2018-09-20
- shell:syntax error:unexpected end of file/Starting prox
- Bootstrap datatable自适应宽度
- 模式匹配Scala Map类型
- scala – 使用typedcolumn选择Spark数据集
- bash – 什么是间接扩展? ${!var *}是什么意思?
- Bootstrap入门之表单