網站搜尋

typescript - 如何使用 Angular 2 路由重新載入當前路由


我正在使用 Angular 2 並搭配 hashlocation 策略。

該組件已經載入了那個路由:

"departments/:id/employees"

到目前為止還好。

在我成功批量保存多個已編輯的表格行後,我想通過以下方式重新加載當前路由 URL:

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

但是什麼都沒有發生,為什麼?

答案#1

在控制器中建立一個函數,將其重定向到預期的路由,如下所示:

redirectTo(uri: string) {
  this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
    this.router.navigate([uri])});
}

然後你這樣使用它

this.redirectTo('//place your uri here');

此功能將重新導向到一個虛擬路由,並在用戶不知情的情況下快速返回目的地路由。

答案#2

這現在可以在 Angular 5.1 中使用 Router 配置的 onSameUrlNavigation 屬性來完成。

我已經添加了一篇說明如何操作的部落格文章,但重點如下

https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

在您的路由器配置中啟用 onSameUrlNavigation 選項,將其設置為 'reload'。這會導致當您嘗試導航到已經處於活動狀態的路由時,路由器觸發事件循環。

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
 exports: [RouterModule],
 })

在你的路由定義中,將 runGuardsAndResolvers 設置為 always。這將告訴路由器始終啟動守衛和解析器的循環,觸發相關事件。

export const routes: Routes = [
 {
   path: 'invites',
   component: InviteComponent,
   children: [
     {
       path: '',
       loadChildren: './pages/invites/invites.module#InvitesModule',
     },
   ],
   canActivate: [AuthenticationGuard],
   runGuardsAndResolvers: 'always',
 }
]

最後,在每個你想要啟用重新加載的組件中,你需要處理事件。這可以通過導入路由器、綁定到事件並調用一個初始化方法來完成,該方法會重置組件的狀態,並在需要時重新獲取數據。

export class InviteComponent implements OnInit, OnDestroy {
 navigationSubscription;     

 constructor(
   // … your declarations here
   private router: Router,
 ) {
   // subscribe to the router events. Store the subscription so we can
   // unsubscribe later.
   this.navigationSubscription = this.router.events.subscribe((e: any) => {
     // If it is a NavigationEnd event re-initalise the component
     if (e instanceof NavigationEnd) {
       this.initialiseInvites();
     }
   });
 }

 initialiseInvites() {
   // Set default values and re-fetch any data you need.
 }

 ngOnDestroy() {
   if (this.navigationSubscription) {
     this.navigationSubscription.unsubscribe();
   }
 }
}

在完成所有這些步驟後,你應該已經啟用了路由重新加載。

答案#3

我正在將這個用於 Angular 11 專案:

reloadCurrentRoute() {
  const currentUrl = this.router.url;
  this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
    this.router.navigate([currentUrl]);
  });
}

附註:已測試,適用於所有高於版本 7 的版本。

答案#4

編輯

對於更新版本的 Angular(5.1+),請使用 @Simon McClive 提出的答案

舊答案

我在 GitHub 上的一個關於 Angular 的功能請求中找到這個變通方法:

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 函數中,確實有效。現在對同一個連結的所有後續點擊都會重新加載 component 和數據。

原始 GitHub 功能請求連結

功勞歸於 GitHub 上的 mihaicux2。

我在版本 4.0.0-rc.3 上測試了這個,使用了 import { Router, NavigationEnd } from '@angular/router';

答案#5

這是我使用 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'
},

答案#6

如果你的 navigate() 不改變已經顯示在瀏覽器地址欄的 URL,那麼路由器無事可做。刷新資料不是路由器的工作。如果你想刷新資料,可以在組件中注入一個服務,並調用服務上的 load 函數。如果新的資料被獲取,它會通過綁定來更新視圖。

答案#7

這對我來說非常有效

this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));

答案#8

有點棘手:使用相同的路徑加上一些虛擬參數。例如-

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

答案#9

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

答案#10

在參數更改時,頁面不會重新加載。這真的是一個很好的功能。沒有必要重新加載頁面,但我們應該更改組件的值。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) {

}