我使用的是带有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`]);
但是什么都没有发生,为什么?
当前回答
这招对我很管用:
let url = `departments/${this.id}/employees`;
this.router.navigated = false;
this.router.navigateByUrl(url);
其他回答
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';
});
使用“时间戳”是一种廉价而神奇的方法。
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
...this.route.snapshot.queryParams,
// replace 't' with any others not to conflict with exsiting
// '2^11' prevents reloading in about 2 seconds
t: Date.now() >> 11,
skipLocationChange: true,
},
});
非常令人沮丧的是,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));
}
}
找到了一个快速而直接的解决方案,不需要修补angular的内部工作原理:
基本上:只需创建一个具有相同目标模块的备用路由,并在它们之间切换:
const routes: Routes = [
{
path: 'gesuch',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
},
{
path: 'gesuch-neu',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
}
];
这里是切换菜单:
<ul class="navigation">
<li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
<li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
</ul>
希望能有所帮助。