如何在Angular 4 中为相同的路线link 召回组件控制器?

How to recall component controller in Angular 4 for the same route link?

我有两个路由 links:

/article/1
/article/2

这些 link 与同一组件相关:

{path: 'article/:id', component: HomeComponent}

初始化组件时,点击 link /article/2 后不会再次初始化此组件。

如何修复?

HTML 是:

 <div (click)="setCurrentRole(role)" *ngFor="let item of menuService.getMenuItems(role)"><a
                [routerLink]="[item.url]" (click)="setActiveLink(i, item.url)" [routerLinkActive]="['is-active']">{{item.title
                | translate}}</a></div>

重新加载组件:

在您的组件中,在 init 挂钩上,订阅路由事件,并将您的 init 代码移动到一个函数中

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params.subscribe(params => {
    console.log(params['id']);
    this.doOnInit();
  });
}

doOnInit() {
  // your old code here
}

正在订阅路由器事件:

constructor(private router: Router) {}

ngOnInit() {
  this.router.events.subscribe(events => {
    // Several routing events, take only the last one
    if (events instanceof NavigationEnd || events.constructor.name === NavigationEnd.name) {
      console.log(params['id']);
      this.doOnInit();
    }
  });
}

doOnInit() {
  // your old code here
}

您只对您在 url 中更改的 ID 感兴趣 那么你可以做类似的事情

    id: number;

  constructor(private route: ActivatedRoute){}

  ngOnInit() {
    this.id = +this.route.snapshot.params['id'];
    this.route.params.subscribe(
      params => {
        /// this method will called if you navigate to different id
        this.id = +params['id'];
      }
    )
  }