[英]Parent route OnInit triggers when navigating to first child
I have an issue that when I change route to a child route, the parent route's OnInit
triggers.我有一个问题,当我将路由更改为子路由时,父路由的
OnInit
会触发。 If I have 3 children, the parent will init maximum 3 times (each for children, when I navigate to the children on the first time).如果我有 3 个孩子,父母将最多初始化 3 次(每次针对孩子,当我第一次导航到孩子时)。
I know it happens due to my CustomReuseStrategy
but I dont know exactly why and how to fix it (I copied the CustomReuseStrategy from somewhere else)我知道这是由于我的
CustomReuseStrategy
而发生的,但我不知道确切的原因以及如何解决它(我从其他地方复制了 CustomReuseStrategy)
I was able to solve it using a different custom reuse strategy我能够使用不同的自定义重用策略来解决它
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
}
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) {
return null;
}
return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
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, '_');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.