項(xiàng)目要求:
a頁(yè)面,輸入檢索條件,檢索數(shù)據(jù)渲染list列表數(shù)據(jù),點(diǎn)擊某一條數(shù)據(jù),路由跳轉(zhuǎn)詳情頁(yè)b,
詳情頁(yè)b點(diǎn)擊返回a頁(yè)面,a頁(yè)面不刷新,檢索條件,列表數(shù)據(jù),正常顯示,
路由傳參,可以實(shí)現(xiàn),但是不允許拼接路由url傳參咋辦?
網(wǎng)上看到??angular路由復(fù)用? 比較方便,?別人已經(jīng)寫(xiě)好了 ,正好符合項(xiàng)目的要求,上代碼
新建SimpleReuseStrategy.ts文件(跟app.module.ts同級(jí))
import { RouteReuseStrategy, DefaultUrlSerializer, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';
export class SimpleReuseStrategy implements RouteReuseStrategy {
? ? public static handlers: { [key: string]: DetachedRouteHandle } = {}
? ? private static waitDelete:string
? ? /** 表示對(duì)所有路由允許復(fù)用 如果你有路由不想利用可以在這加一些業(yè)務(wù)邏輯判斷 */
? ? public shouldDetach(route: ActivatedRouteSnapshot): boolean {
? ? ? ? return true;
? ? }
? ? /** 當(dāng)路由離開(kāi)時(shí)會(huì)觸發(fā)矢棚。按path作為key存儲(chǔ)路由快照&組件當(dāng)前實(shí)例對(duì)象 */
? ? public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
? ? ? ? if(SimpleReuseStrategy.waitDelete && SimpleReuseStrategy.waitDelete==this.getRouteUrl(route)){
? ? ? ? ? ? //如果待刪除是當(dāng)前路由則不存儲(chǔ)快照
? ? ? ? ? ? SimpleReuseStrategy.waitDelete=null
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? SimpleReuseStrategy.handlers[this.getRouteUrl(route)] = handle
? ? }
? ? /** 若 path 在緩存中有的都認(rèn)為允許還原路由 */
? ? public shouldAttach(route: ActivatedRouteSnapshot): boolean {
? ? ? ? return !!SimpleReuseStrategy.handlers[this.getRouteUrl(route)]
? ? }
? ? /** 從緩存中獲取快照,若無(wú)則返回nul */
? ? public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
? ? ? ? if (!route.routeConfig) {
? ? ? ? ? ? return null
? ? ? ? }
? ? ? ? return SimpleReuseStrategy.handlers[this.getRouteUrl(route)]
? ? }
? ? /** 進(jìn)入路由觸發(fā)贷痪,判斷是否同一路由 */
? ? public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {? ? ? ?
? ? ? ? return future.routeConfig===curr.routeConfig &&
? ? ? ? ? ? JSON.stringify(future.params)==JSON.stringify(curr.params);
? ? }
? ? private getRouteUrl(route: ActivatedRouteSnapshot){
? ? ? ? return route['_routerState'].url.replace(/\//g,'_')
? ? }? ? public static deleteRouteSnapshot(name:string):void{
? ? ? ? if(SimpleReuseStrategy.handlers[name]){
? ? ? ? ? ? delete SimpleReuseStrategy.handlers[name];
? ? ? ? }else{
? ? ? ? ? ? SimpleReuseStrategy.waitDelete=name;
? ? ? ? }
? ? }
}
注冊(cè)到模塊當(dāng)中(添加到app.mould.ts中)