我使用的是带有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`]);
但是什么都没有发生,为什么?
当前回答
在route.navigate()的方法中实现OnInit并调用ngOnInit()
请看一个例子:
export class Component implements OnInit {
constructor() { }
refresh() {
this.router.navigate(['same-route-here']);
this.ngOnInit(); }
ngOnInit () {
}
其他回答
我在Angular 11项目中使用这个:
reloadCurrentRoute() {
const currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
PS:测试和工作在所有版本以上7。
非常令人沮丧的是,Angular似乎仍然没有提供一个好的解决方案。我在这里提出了一个github问题:https://github.com/angular/angular/issues/31843
与此同时,这是我的变通办法。它建立在上面建议的一些其他解决方案的基础上,但我认为它更健壮一些。它涉及到将Router服务包装在一个“ReloadRouter”中,该服务负责重载功能,并将RELOAD_PLACEHOLDER添加到核心路由器配置中。这用于临时导航,避免触发任何其他路线(或警卫)。
注意:只有在需要重载功能的情况下才使用ReloadRouter。否则使用普通路由器。
import { Injectable } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ReloadRouter {
constructor(public readonly router: Router) {
router.config.unshift({ path: 'RELOAD_PLACEHOLDER' });
}
public navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
return this.router
.navigateByUrl('/RELOAD_PLACEHOLDER', {skipLocationChange: true})
.then(() => this.router.navigate(commands, extras));
}
}
写一个函数。, reloadCurrentPage。由于window是一个全局对象,可以直接在Angular组件中重用,window.location.reload()会重新加载当前活动的页面。
function reloadCurrentPage() {
window.location.reload();
}
Angular 2-4路由重载破解
对我来说,在根组件(组件,存在于任何路由)中使用这个方法是有效的:
onRefresh() {
this.router.routeReuseStrategy.shouldReuseRoute = function(){return false;};
let currentUrl = this.router.url + '?';
this.router.navigateByUrl(currentUrl)
.then(() => {
this.router.navigated = false;
this.router.navigate([this.router.url]);
});
}
有点硬核,但是
this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl(this.router.url).then(() => {
this.router.onSameUrlNavigation = 'ignore';
});