Angular点击菜单刷新页面

2018-09-18  本文已影响0人  _红桃K

点击菜单刷新页面

当前的问题是,当登录到系统后,只有第一次点击目录的时候才刷新,后面再次点击无反应,需要手动刷新页面,客户嫌麻烦,因此在网上搜了下,一共找到了四种方法,在此先做记录,遇到问题都可以尝试下,以备不时之需

  <a ui-sref="page" ui-sref-opts="{reload:true,notify:true}">链接</a>
  $state.go('page',,{reload:true});
  <app-view cache-view="false"></app-view>
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';

export class AppRoutingCache implements RouteReuseStrategy{
    public static handlers: { [key: string]: DetachedRouteHandle } = {};
    // 表示对路由允许复用
    public shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return false;
    }
    // 当路由离开时会触发
    public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        AppRoutingCache.handlers[route.routeConfig.path] = handle;
    }
    // 若path在缓存中有的都认为允许还原路由
    public shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!AppRoutingCache.handlers[route.routeConfig.path];
    }
    // 从缓存中获取快照,若无则返回null
    public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig) {
            return null;
        }
        return AppRoutingCache.handlers[route.routeConfig.path];
    }
    // 进入路由触发,判断是否同一路由
    public shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
        return future.routeConfig == current.routeConfig;
    }
}

然后在app.module.ts中添加:

import { RouteReuseStrategy } from '@angular/router';
import { AppRoutingCache } from './app-routing.cache';
providers: [
  { provide: RouteReuseStrategy, useClass: AppRoutingCache },
]

这样就可以了,以上第四种方法是我现在项目中用到的,在我这可行,对于其他的项目,有待尝试。

上一篇 下一篇

猜你喜欢

热点阅读