簡體   English   中英

Angular 多次導航到同一組件

[英]Angular navigate to the same component more then one time

我試圖通過在導航欄中使用 [routerlink] 導航到相同的路線。 因為在 angular 中,重定向到同一個組件來調用 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]);
  }

第一次點擊路由器導航后的路由器鏈接是這樣的

/客戶/事件/進行中/sda3i4un34j3b42

但是當我嘗試單擊相同的導航按鈕時,路由器鏈接如下所示

/客戶/事件/

這里的問題不是調用 getfunction() 和 OnInit 誰能弄明白?

謝謝

你應該做一個函數重定向來啟用 shouldreusestartergy

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

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

}

每當您想重新加載並調用所有 Angular 生命周期鈎子時,請調用此 reInitComponent()

我們可以添加一個動態變化的查詢參數。

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

因此,我們可以檢查構造函數中的查詢參數是否更改並傳遞我們需要執行的函數。

使用這種方法可以修復路由到具有不同參數的同一組件的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM