我使用的是带有hashlocation策略的angular 2。

组件是用这个路由加载的:

"departments/:id/employees"

到目前为止还好。

在我成功批量保存多个编辑表行后,我想通过以下方式重新加载当前路由URL:

this.router.navigate([`departments/${this.id}/employees`]);

但是什么都没有发生,为什么?


当前回答

决定何时存储路由返回false

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
};

并将router的导航值设置为false,表示该路由从未被路由

this.mySubscription = this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        this.router.navigated = false;
    }
});

其他回答

订阅路由参数更改

    // parent param listener ie: "/:id"
    this.route.params.subscribe(params => {
        // do something on parent param change
        let parent_id = params['id']; // set slug
    });

    // child param listener ie: "/:id/:id"
    this.route.firstChild.params.subscribe(params => {
        // do something on child param change
        let child_id = params['id'];
    });

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]);
    });
  }

另一种选择是使用纯js,但页面实际上会刷新。

window.location.reload(true)

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 ';

这就是我在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'
},