问题描述
是否可以在 ReuseStrategy 中检索路由器的 navigationTrigger。例如,当事件是 NavigationStart 的实例时,此属性在路由器事件中可用。 这是我需要的:
- 当用户使用位置向后或向前导航时,ReuseStrategy 应仅重用组件。 我想像这样实现它:
应用组件:
import { NavigationStart,Router } from '@angular/router';
import { CustomreuseStrategy } from './common/services/custom-reuse-strategy.service';
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.sass']
})
export class AppComponent {
constructor(private router: Router,private reuseStrat: CustomreuseStrategy) {
this.router.events.subscribe((val) => {
if(val instanceof NavigationStart){
console.log(val.navigationTrigger);
this.reuseStrat.setNavigationTrigger(val.navigationTrigger);
}
});
}
}
自定义重用策略:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot,RouteReuseStrategy,DetachedRouteHandle,UrlSegment } from '@angular/router'
@Injectable({
providedIn: 'root'
})
export class CustomreuseStrategy implements RouteReuseStrategy {
storedHandles: { [key: string]: DetachedRouteHandle } = {};
popStateEvent: string;
setNavigationTrigger(value){
console.log(value);
this.popStateEvent = value;
console.log(this.popStateEvent);
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.data.reuseRoute || false;
}
store(route: ActivatedRouteSnapshot,handle: DetachedRouteHandle): void {
const id = this.createIdentifier(route);
this.storedHandles[id] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
const id = this.createIdentifier(route);
const handle = this.storedHandles[id];
const canAttach = !!route.routeConfig && !!handle;
return canAttach;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
const id = this.createIdentifier(route);
if (!route.routeConfig || !this.storedHandles[id]) return null;
return this.storedHandles[id];
}
shouldReuseRoute(future: ActivatedRouteSnapshot,curr: ActivatedRouteSnapshot): boolean {
const routeVisited = this.createIdentifier(future) === this.createIdentifier(curr);
console.log('reuseRoute');
console.log(this.popStateEvent);
return routeVisited;
}
private createIdentifier(route: ActivatedRouteSnapshot) {
// Build the complete path from the root to the input route
const segments: UrlSegment[][] = route.pathFromroot.map(r => r.url);
const subpaths = ([] as UrlSegment[]).concat(...segments).map(segment => segment.path);
// Result: path
return subpaths.join('/');
}
}
我添加了一些日志,但是我在 shouldReuseRoute 函数中的 popStateEvent 变量始终未定义,但是在上面您可以看到该函数已被触发并且值也已设置。我错过了什么吗?这里的日志:
我还检查了 ActivatedRouteSnapshot 变量,如果 navigationTrigger 存储在某处,但我找不到任何东西。 也许我想存档的方式完全错误,所以请随时提出其他想法或解决方案:)
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)