我有一个组件 MainPageComponent。当用户从顶部菜单中单击“主页”时,我的自定义 RouteReuseStrategy 会从内存中恢复“主页”路线,用户从他离开的地方选择。我怎样才能在这个恢复组件的代码中知道它何时被恢复并恢复活动?
我假设 ngOnInit 没有被调用,因为这不是组件 init,但它已经启动并运行。RouteReuseStrategy 在恢复时是否对组件调用了某些方法?
我不知道是否相关,但这是我使用的自定义 RouteReuseStrategy 组件。此处“主页”的路由将在 routesToStore 数组中 - 这些路由根据请求从内存中恢复。
import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';
interface RouteStorageObject {
snapshot: ActivatedRouteSnapshot;
handle: DetachedRouteHandle;
}
export class CustomReuseStrategy implements RouteReuseStrategy {
constructor() {
// Determine which routes to preserve
this.routesToStore = ["search", "favorites", "explore"];
}
routesToStore: string[];
storedRoutes: { [key: string]: RouteStorageObject } = {}
// If returns false, user is let to leave current view
shouldReuseRoute (future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
// Return false if navigating to another route than current
return future.routeConfig === current.routeConfig;
}
// Should the route be stored?
shouldDetach(route: ActivatedRouteSnapshot): boolean {
// Keep state of all routes by always returning true
if (this.routesToStore.indexOf(route.routeConfig.path) > -1)
return true;
return false;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
let storedRoute: RouteStorageObject = {
snapshot: route,
handle: handle
};
this.storedRoutes[route.routeConfig.path] = storedRoute;
}
// Should the component state be restored?
shouldAttach(route: ActivatedRouteSnapshot): boolean {
// If the route has been stored before
let canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];
if (canAttach)
return true;
return false;
}
// Retrieve the component state
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;
return this.storedRoutes[route.routeConfig.path].handle;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以(activate)在 上使用事件<router-outlet>。
https://netbasal.com/angular-2-router-routeroutlet-events-8b0803d88082
因此,在您的页面中处理该事件app.component.html:
<router-outlet (activate)="onActivate($event)"></router-outlet>
Run Code Online (Sandbox Code Playgroud)
在你的app.component.ts:
// yes - the $event is the component itself
onActivate(component)
{
if (component["onActivate"])
{
component.onActivate();
}
// [optional] tell your shared service
this.pageManagerService.activeComponent.next(component);
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个简单的页面管理器服务,当激活新组件时会通知该服务。这是共享的,因此我可以将其注入到任何我想要的地方。它控制菜单如何根据当前组件、页面背景颜色等显示。
(与@Su-Au Hwang提出的问题类似的想法)
| 归档时间: |
|
| 查看次数: |
665 次 |
| 最近记录: |