在Angular中,可以使用RouteReuseStrategy
来重新加载延迟加载的父组件。下面是一个包含代码示例的解决方法:
RouteReuseStrategy
类,该类将用于重新加载延迟加载的父组件。import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return false;
}
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return false;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
return null;
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return false;
}
}
app.module.ts
中,将自定义的RouteReuseStrategy
提供给RouterModule
。import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, RouteReuseStrategy } from '@angular/router';
import { AppComponent } from './app.component';
import { CustomRouteReuseStrategy } from './custom-route-reuse-strategy';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, RouterModule.forRoot([...])],
providers: [
{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
RouterNavigationEnd
事件来手动重新加载父组件。import { Component } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
@Component({
selector: 'app-parent',
template: `
Parent Component
...
`
})
export class ParentComponent {
constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd && event.id === 1) {
// 判断是否为初次加载
const currentRoute = this.activatedRoute.root.firstChild.snapshot.routeConfig;
if (currentRoute && currentRoute.loadChildren) {
// 重新加载父组件
this.router.navigated = false;
this.router.navigate([currentRoute.path]);
}
}
});
}
}
通过使用自定义的RouteReuseStrategy
和手动重新加载父组件,可以实现延迟加载的父组件的重新加载。
下一篇:Angular 路由的问题