我有一个带导航栏的 Angular 应用程序。当用户重新单击与当前页面匹配的链接时,我收到了刷新组件数据的请求。稍作阅读后,我了解到我需要将 onSameUrlNavigation 设置为“重新加载”并捕获组件中的事件并刷新其中的数据。虽然我知道这是最好的解决方案并且不需要重新创建组件,但我正在尝试为我的所有路由找到一些快速修复,而无需编写大量代码来支持此行为。当新路线与当前路线匹配时,有没有一种方法可以强制销毁所有组件并重新创建?也许在 router-outlet 或其他一些快速修复上创建某种指令?
最好的, 塔尔休米
最佳答案
我刚遇到一个问题,从 /user/1/roles
到 /user/2/roles
的导航重新使用了与 关联的组件/Angular 色
。这是因为默认情况下,Angular 更喜欢尽可能重用组件,以提高内存效率。
首先创建一个CUSTOM ROUTE REUSE STRAGETY,如下所示:
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
export class DefaultRouteReuseStrategy 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; // <-- Here is the critical line of code which forces re-creation of the component
}
}
并将其注册到您的 AppModule 中,如下所示:
@NgModule({
providers: [
{
provide: RouteReuseStrategy,
useClass: DefaultRouteReuseStrategy,
},
],
})
AppModule {}
关于javascript - Angular - 在自路由更改时重新创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61854387/