我使用的是带有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 12中所做的。我不确定这是否适用于9以下的版本。
当您需要重新加载时,您将需要调用它。
this.router.navigate([], {
skipLocationChange: true,
queryParamsHandling: 'merge' //== if you need to keep queryParams
})
Router forRoot需要将SameUrlNavigation设置为“reload”
RouterModule.forRoot(appRoutes, {
// ..
onSameUrlNavigation: 'reload',
// ..
})
你的每个路径都需要将runGuardsAndResolvers设置为always
{
path: '',
data: {},
runGuardsAndResolvers: 'always'
},
其他回答
我相信这个问题已经在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
对我来说是硬编码
this.router.routeReuseStrategy.shouldReuseRoute = function() {
return false;
// or
return true;
};
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]);
});
}
重载当前路由在angular 2非常有用的链接重载当前路由在angualr 2或4
在这里定义两种技术来做到这一点
使用虚拟查询参数 使用虚拟路由
欲了解更多信息,请参见上面的链接
非常令人沮丧的是,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));
}
}