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

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

"departments/:id/employees"

到目前为止还好。

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

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

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


当前回答

小技巧: 使用相同的路径和一些虚拟参数。例如,

refresh(){
  this.router.navigate(["/same/route/path?refresh=1"]);
}

其他回答

我相信这个问题已经在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

在我的例子中:

const navigationExtras: NavigationExtras = {
    queryParams: { 'param': val }
};

this.router.navigate([], navigationExtras);

正确的工作

如果你的navigate()没有改变浏览器地址栏上已经显示的URL,路由器就不需要做什么。刷新数据不是路由器的工作。如果希望刷新数据,可以创建一个注入到组件中的服务,并调用该服务上的加载函数。如果将检索新数据,它将通过绑定更新视图。

从@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。

在参数更改时,重新加载页面将不会发生。这是一个很好的特性。不需要重新加载页面,但我们应该改变组件的值。paramChange方法将在url更改时调用。所以我们可以更新组件数据

/product/: id / details

import { ActivatedRoute, Params, Router } from ‘@angular/router’;

export class ProductDetailsComponent implements OnInit {

constructor(private route: ActivatedRoute, private router: Router) {
    this.route.params.subscribe(params => {
        this.paramsChange(params.id);
    });
}

// Call this method on page change

ngOnInit() {

}

// Call this method on change of the param
paramsChange(id) {

}