route-reuse.service.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {
  2. ActivatedRouteSnapshot,
  3. DetachedRouteHandle,
  4. RouteReuseStrategy,
  5. } from '@angular/router';
  6. export class ReuseService implements RouteReuseStrategy {
  7. storedRouteHandles = new Map<string, DetachedRouteHandle>();
  8. //用来判断跳转时是否需要存储页面
  9. from = '';
  10. to = '';
  11. //用来判断跳转时是否要读取之前存储的页面
  12. reuseFrom = '';
  13. reuseTo = '';
  14. shouldReuseRoute(
  15. from: ActivatedRouteSnapshot,
  16. to: ActivatedRouteSnapshot
  17. ): boolean {
  18. if (from.routeConfig) {
  19. this.from = this.getPath(from);
  20. }
  21. if (to.routeConfig) {
  22. this.to = this.getPath(to);
  23. }
  24. return from.routeConfig === to.routeConfig;
  25. }
  26. shouldDetach(route: ActivatedRouteSnapshot): boolean {
  27. console.log(this.from);
  28. console.log(this.to);
  29. // 判断是否执行store
  30. const f =
  31. (this.from === 'nav-admin/manage/user' && this.to === 'nav-admin/manage/user/edit') ||
  32. (this.from === 'b' && this.to === 'c');
  33. if (f) {
  34. this.reuseFrom = this.to;
  35. this.reuseTo = this.from;
  36. }
  37. return f;
  38. }
  39. store(
  40. route: ActivatedRouteSnapshot,
  41. detachedTree: DetachedRouteHandle
  42. ): void {
  43. // 进行路由复用存储
  44. this.storedRouteHandles.set(this.getPath(route), detachedTree);
  45. }
  46. retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
  47. if (this.from === this.reuseFrom && this.to === this.reuseTo) {
  48. // 读取路由复用
  49. return this.storedRouteHandles.get(
  50. this.getPath(route)
  51. ) as DetachedRouteHandle;
  52. } else {
  53. return null;
  54. }
  55. }
  56. shouldAttach(route: ActivatedRouteSnapshot): boolean {
  57. if (this.reuseFrom && this.reuseTo && this.from && this.to) {
  58. return this.from === this.reuseFrom && this.to === this.reuseTo;
  59. } else {
  60. return false;
  61. }
  62. }
  63. private getPath(route: ActivatedRouteSnapshot | any): string {
  64. // 截取路由地址中最小子节点
  65. let url = route['_routerState'].url.split('/');
  66. return url[url.length - 1].split('?')[0];
  67. }
  68. }