角度导航到同一组件超过一次

时间:2020-02-10 16:32:46

标签: angular typescript rxjs angular-resolver

我正在尝试通过导航栏上的[routerlink]导航到相同的路线。 因为在角度,重定向到同一组件以调用ngOnint是不可能的,我遇到了这个问题。

在导航栏上导航

[routerLink]="['/customer/events']"

构造函数中的代码

  constructor(
     private navbarService: ServicesInterCustomerNavbarService,
     private router: Router,
     private route: ActivatedRoute
  ) {
     this.route.params.subscribe(params => {
       this.selectedEventId = params["id"];
       this.getfunction();
    });
 }

我的ngOnInit如下所示

ngOnInit() {
    this.ongoing = [];
    this.navbarService.sendCurrentRoute("home");
    this.route.firstChild && this.route.firstChild.params.subscribe(params => {
      this.selectedEventId = params["id"];
      this.getfunction();
    });
}
getfunction() {
    this.ongoing = [];
    this.eventService.getOnging().subscribe(data => {
      this.ongoingEvents = data["data"].map(event => new CustomerEvent(event));
      if (!this.selectedEventId && this.selectedEventId != 'completed' && this.ongoingEvents.length >0) {
        this.redirectToEvent(this.ongoingEvents[0]._id);
      }
      if(this.ongoingEvents.length <1){
        this.redirectToEvent('-1');
      }
      this.dataLoaded = true;
    });
  }

  eventCreated(event_id: string) {
    this.router.navigate(["/customer/events/ongoing", event_id]);
    this.newEventWindow = false;

  }

  redirectToEvent(event_id: string) {
    this.router.navigate(["/customer/events/ongoing", event_id]);
  }

首次单击路由器导航后的路由器链接类似于

/ customer / events / ongoing / sda3i4un34j3b42

但是当我尝试单击相同的导航按钮时,路由器链接如下所示

/ customer / events /

这里的问题不是调用getfunction()和OnInit 谁能解决这个问题?

谢谢

2 个答案:

答案 0 :(得分:1)

您应该只进行函数重定向,以启用shouldreusestartergy

reInitComponent(){
this.router.routeReuseStrategy.shouldReuseRoute = () => false;

this.router.navigate(["/customer/events/ongoing", event_id]);

}

每当您要重新加载并调用所有角度生命周期挂钩时,请调用此reInitComponent()

答案 1 :(得分:0)

我们可以添加动态更改的查询参数。

this.router.navigate(['/routedComponent'], {
   queryParams: {refresh: new Date().getTime()}
});

因此,我们可以检查构造函数中查询参数是否已更改,并传递需要执行的函数。

通过这种方法,可以解决路由到具有不同参数的相同组件的问题

相关问题