我有一个带有导航栏的angular应用。当用户重新点击与当前页面匹配的链接时,我收到了一个刷新组件数据的请求。经过一番阅读,我明白了我需要将onSameUrlNavigation设置为 "reload",并在组件中捕获事件并刷新其中的数据。虽然我知道这是最好的解决方案,而且不需要重新创建组件,但我试图为我所有的路由找到一些快速的修复方法,而不需要编写大量的代码来支持这种行为。有没有一种方法可以强制我所有的组件被销毁,并在新的路由与当前路由匹配时重新创建,也许可以在路由器出口上创建某种指令或其他快速修复方法?
最好的,Tal Humy
我有一个带导航栏的angular app。当用户重新点击与当前页面匹配的链接时,我收到了一个刷新组件数据的请求。
如何 导航栏 构建的?是一个数组的 li a
元素与 [routerLink]
绑定?如果是这样,你可以把它改成 (click)=refreshOrGoToPage(path, $event)
绑定,并在事件处理程序中做必要的事情。
例子
import { Router } from '@angular/router';
constructor(private _router: Router) {}
refreshOrGoToPage(path: string, event: MouseEvent) {
if(this._router.url === path) {
this.refreshData();
return;
}
this.router.navigate([path, {}]);
}
--编辑
这里有一个有趣的
如果你手动导航到路线,你可以先导航到一个空的路线,然后再导航到你想要的路线。
你可以把上面的例子代码改成。
if(this._router.url === path) {
const emptyPath = '/reload';
this.router.navigate([emptyPath, {}]).then(_ => {
this.router.navigate([path, {}])
})
return;
}
你可以订阅 路由器 类这样。
protected previousUrl: string = '';
protected currentUrl: string = '';
在构造函数中:
constructor(
private _router: Router,
) { }
在你的ngOnInit(或其他地方)中,
this._router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
}
});
我刚刚遇到一个问题,一个导航从... /user/1/roles
到 /user/2/roles
是重复使用与 /roles
. 这是因为在默认情况下,Angular更愿意在可能的情况下重用组件,以提高内存效率。
首先创建一个 定制路线再利用策略。 如下所示。
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 {}