我使用的是带有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`]);
但是什么都没有发生,为什么?
当前回答
从@angular/ Router中导入Router和ActivatedRoute
import { ActivatedRoute, Router } from '@angular/router';
注入Router和ActivatedRoute(以防你需要URL中的任何东西)
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
从URL中获取所需的任何参数。
const appointmentId = this.route.snapshot.paramMap.get('appointmentIdentifier');
使用一个技巧,通过导航到一个虚拟url或主url,然后到实际url将刷新组件。
this.router.navigateByUrl('/appointments', { skipLocationChange: true }).then(() => {
this.router.navigate([`appointment/${appointmentId}`])
});
在你的情况下
const id= this.route.snapshot.paramMap.get('id');
this.router.navigateByUrl('/departments', { skipLocationChange: true }).then(() => {
this.router.navigate([`departments/${id}/employees`]);
});
如果你使用一个虚拟路由,那么你会看到一个标题闪烁'未找到',如果你已经实现了一个未找到的url,以防不匹配任何url。
其他回答
在route.navigate()的方法中实现OnInit并调用ngOnInit()
请看一个例子:
export class Component implements OnInit {
constructor() { }
refresh() {
this.router.navigate(['same-route-here']);
this.ngOnInit(); }
ngOnInit () {
}
有点硬核,但是
this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});
有不同的方法来刷新当前路由
改变路由器的行为(从Angular 5.1开始) 设置路由器onSameUrlNavigation为“reload”。这将在相同的URL导航上发出路由器事件。
然后,您可以通过订阅路由来处理它们 您可以将它与runGuardsAndResolvers组合使用以重新运行解析器
不动路由器
在URL和中传递一个带有当前时间戳的刷新queryParam 订阅路由组件中的queryParams。 使用路由器出口的激活事件来获取一个 保持路由组件。
我已经在https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6e下写了更详细的解释
希望这能有所帮助。
我尝试了一些修复方法,但没有一个有效。我的版本很简单:在查询参数中添加一个新的未使用的参数
if (force) {
let key = 'time';
while (key in filter) {
key = '_' + key;
}
filter[key] = Date.now();
}
this.router.navigate(['.', { filter: JSON.stringify(filter) }]);
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 ';