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

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

“真誠服務(wù),讓網(wǎng)絡(luò)創(chuàng)造價(jià)值”是我們的服務(wù)理念,創(chuàng)新互聯(lián)建站團(tuán)隊(duì)十年如一日始終堅(jiān)持在網(wǎng)站建設(shè)領(lǐng)域,為客戶提供優(yōu)質(zhì)服。不管你處于什么行業(yè),助你輕松跨入“互聯(lián)網(wǎng)+”時(shí)代,PC網(wǎng)站+手機(jī)網(wǎng)站+公眾號(hào)+小程序定制開發(fā)。

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

重復(fù)點(diǎn)擊同一鏈接頁面不會(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事件,頁面是不會(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)前頁面的幾種方法:

NavigationEnd

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

訂閱Router Event,在NavigationEnd中重新加載數(shù)據(jù),銷毀組件時(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();
    }
  }
  ...
}

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

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為單例對象,因此使用這種方式,在一個(gè)組件中更改策略后會(huì)影響其他組件,但從瀏覽器刷新頁面后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)前頁面的幾種方法

網(wǎng)站題目:Angular刷新當(dāng)前頁面的幾種方法
標(biāo)題網(wǎng)址:http://muchs.cn/article26/ghegcg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作用戶體驗(yàn)、營銷型網(wǎng)站建設(shè)、虛擬主機(jī)網(wǎng)站維護(hù)、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)