我使用的是带有hashlocation策略的angular 2。
组件是用这个路由加载的:
"departments/:id/employees"
到目前为止还好。
在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:
this.router.navigate([`departments/${this.id}/employees`]);
但是什么都没有发生,为什么?
我使用的是带有hashlocation策略的angular 2。
组件是用这个路由加载的:
"departments/:id/employees"
到目前为止还好。
在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:
this.router.navigate([`departments/${this.id}/employees`]);
但是什么都没有发生,为什么?
当前回答
解决方案:
订阅URL参数并在那里初始化组件。没有技巧,只是“新URL ->新数据”,包括第一次加载。
对于URL参数(如/persons/:id):
constructor(protected activeRoute: ActivatedRoute, ...) {
this.activeRoute.paramMap.subscribe(paramMap => {
const id = paramMap.get('id'); // get param from dictonary
this.load(id); // load your data
});
}
对于URL查询参数(比如?q=…&returnUrl=…)(通常不是必需的):
this.activeRoute.queryParamMap.subscribe(queryParamMap => {
const returnUrl = queryParamMap.get('returnUrl');
...
});
问题的原因是:
当URL发生变化时,Angular会尽可能重用旧的组件,以节省计算机资源。加载数据是你的自定义代码,所以Angular不能为你做这件事。
其他回答
有不同的方法来刷新当前路由
改变路由器的行为(从Angular 5.1开始) 设置路由器onSameUrlNavigation为“reload”。这将在相同的URL导航上发出路由器事件。
然后,您可以通过订阅路由来处理它们 您可以将它与runGuardsAndResolvers组合使用以重新运行解析器
不动路由器
在URL和中传递一个带有当前时间戳的刷新queryParam 订阅路由组件中的queryParams。 使用路由器出口的激活事件来获取一个 保持路由组件。
我已经在https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6e下写了更详细的解释
希望这能有所帮助。
在我的例子中:
const navigationExtras: NavigationExtras = {
queryParams: { 'param': val }
};
this.router.navigate([], navigationExtras);
正确的工作
EDIT
对于较新版本的Angular(5.1+),请使用@Simon McClive建议的答案
旧的答案
我在一个针对Angular的GitHub特性请求中找到了这个解决方案:
this._router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
this._router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this._router.navigated = false;
window.scrollTo(0, 0);
}
});
我试着把它添加到我的app.component.ts ngOnInit函数中,它确实工作了。现在,在同一链接上的所有进一步单击都将重新加载组件和数据。
链接到原始GitHub功能请求
感谢GitHub上的mihaicux2。
我在4.0.0-rc版本上进行了测试。导入{Router, NavigationEnd} from '@angular/ Router ';
只需使用本地javascript重载方法:
reloadPage() {
window.location.reload();
}
我相信这个问题已经在Angular 6+中(原生地)解决了;检查
这里https://github.com/angular/angular/issues/13831 && 在这里https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
但这适用于整个路由(包括所有子路由)
如果你想要针对单个组件,以下是方法: 使用可更改的查询参数,以便您可以任意多次导航。
在导航点(类)
this.router.navigate(['/route'], {
queryParams: { 'refresh': Date.now() }
});
在你想要“刷新/重载”的组件中
// . . . Component Class Body
$_route$: Subscription;
constructor (private _route: ActivatedRoute) {}
ngOnInit() {
this.$_route$ = this._route.queryParams.subscribe(params => {
if (params['refresh']) {
// Do Something
// Could be calling this.ngOnInit() PS: I Strongly advise against this
}
});
}
ngOnDestroy() {
// Always unsubscribe to prevent memory leak and unexpected behavior
this.$_route$.unsubscribe();
}
// . . . End of Component Class Body