溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Angular刷新當(dāng)前頁(yè)面的幾種方法

發(fā)布時(shí)間:2020-06-05 13:03:35 來(lái)源:網(wǎng)絡(luò) 閱讀:14678 作者:川川Jason 欄目:web開(kāi)發(fā)

默認(rèn),當(dāng)收到導(dǎo)航到當(dāng)前URL的請(qǐng)求,Angular路由器會(huì)忽略。

<a routerLink="/heroes" routerLinkActive="active">Heroes</a>

重復(fù)點(diǎn)擊同一鏈接頁(yè)面不會(huì)刷新。

從Angular 5.1起提供onSameUrlNavigation屬性,支持重新加載路由。

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

onSameUrlNavigation有兩個(gè)可選值:'reload'和'ignore',默認(rèn)為'ignore'。但僅將onSameUrlNavigation改為'reload',只會(huì)觸發(fā)RouterEvent事件,頁(yè)面是不會(huì)重新加載的,還需配合其它方法。在繼續(xù)之前,我們啟用Router Trace,從瀏覽器控制臺(tái)查看一下路由事件日志:

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

可以看到,未配置onSameUrlNavigation時(shí),再次點(diǎn)擊同一鏈接不會(huì)輸出日志,配置onSameUrlNavigation為'reload'后,會(huì)輸出日志,其中包含的事件有:NavigationStart、RoutesRecognized、GuardsCheckStart、GuardsCheckEnd、ActivationEnd、NavigationEnd等。

下面介紹刷新當(dāng)前頁(yè)面的幾種方法:

NavigationEnd

  1. 配置onSameUrlNavigation為'reload'
  2. 監(jiān)聽(tīng)NavigationEnd事件

訂閱Router Event,在NavigationEnd中重新加載數(shù)據(jù),銷(xiāo)毀組件時(shí)取消訂閱:

export class HeroesComponent implements OnDestroy {
  heroes: Hero[];
  navigationSubscription;

  constructor(private heroService: HeroService, private router: Router) {
    this.navigationSubscription = this.router.events.subscribe((event: any) => {
      if (event instanceof NavigationEnd) {
        this.init();
      }
    });
  }

  init() {
    this.getHeroes();
  }

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

這種方式可按需配置要刷新的頁(yè)面,但代碼煩瑣。

RouteReuseStrategy

  1. 配置onSameUrlNavigation為'reload'
  2. 自定義RouteReuseStrategy,不重用Route

有兩種實(shí)現(xiàn)方式:
在代碼中更改策略:

constructor(private heroService: HeroService, private router: Router) {
  this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };
}

Angular應(yīng)用Router為單例對(duì)象,因此使用這種方式,在一個(gè)組件中更改策略后會(huì)影響其他組件,但從瀏覽器刷新頁(yè)面后Router會(huì)重新初始化,容易造成混亂,不推薦使用。

自定義RouteReuseStrategy:

import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return null;
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return false;
  }

}

使用自定義RouteReuseStrategy:

@NgModule({
  imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
  exports: [RouterModule],
  providers: [
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
  ]
})

這種方式可以實(shí)現(xiàn)較為復(fù)雜的Route重用策略。

Resolve

使用Resolve可以預(yù)先從服務(wù)器上獲取數(shù)據(jù),這樣在路由激活前數(shù)據(jù)已準(zhǔn)備好。

  1. 實(shí)現(xiàn)ResolverService

將組件中的初始化代碼轉(zhuǎn)移到Resolve中:

import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';

import {HeroService} from '../hero.service';
import {Hero} from '../hero';

@Injectable({
  providedIn: 'root',
})
export class HeroesResolverService implements Resolve<Hero[]> {
  constructor(private heroService: HeroService) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Hero[]> | Observable<never> {
    return this.heroService.getHeroes();
  }
}

為路由配置resolve:

path: 'heroes', component: HeroesComponent, canActivate: [CanActivateAuthGuard], resolve: {heroes: HeroesResolverService}
  1. 修改組件代碼,改為從resolve中獲取數(shù)據(jù)
constructor(private heroService: HeroService, private route: ActivatedRoute) {
}

ngOnInit() {
  this.route.data.subscribe((data: { heroes: Hero[] }) => {
    this.heroes = data.heroes;
  });
}
  1. 配置onSameUrlNavigation為'reload'
  2. 配置runGuardsAndResolvers為‘a(chǎn)lways’

runGuardsAndResolvers可選值:'paramsChange' 、'paramsOrQueryParamsChange'、'always'

{path: 'heroes', component: HeroesComponent, canActivate: [CanActivateAuthGuard], resolve: {heroes: HeroesResolverService}, runGuardsAndResolvers: 'always'}

時(shí)間戳

給Router增加時(shí)間參數(shù):

<a (click)="gotoHeroes()">Heroes</a>
constructor(private router: Router) {
}

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

然后在組件中訂閱queryParamMap:

constructor(private heroService: HeroService, private route: ActivatedRoute) {
  this.route.queryParamMap.subscribe(params => {
    if (params.get('refresh')) {
      this.init();
    }
  });
}

2018廣州馬拉松
Angular刷新當(dāng)前頁(yè)面的幾種方法

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI