默認,當收到導航到當前URL的請求,Angular路由器會忽略。瀏覽器
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
重複點擊同一連接頁面不會刷新。服務器
從Angular 5.1起提供onSameUrlNavigation屬性,支持從新加載路由。ide
@NgModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})], exports: [RouterModule] })
onSameUrlNavigation有兩個可選值:'reload'和'ignore',默認爲'ignore'。但僅將onSameUrlNavigation改成'reload',只會觸發RouterEvent事件,頁面是不會從新加載的,還需配合其它方法。在繼續以前,咱們啓用Router Trace,從瀏覽器控制檯查看一下路由事件日誌:this
@NgModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload', enableTracing: true})], exports: [RouterModule] })
能夠看到,未配置onSameUrlNavigation時,再次點擊同一連接不會輸出日誌,配置onSameUrlNavigation爲'reload'後,會輸出日誌,其中包含的事件有:NavigationStart、RoutesRecognized、GuardsCheckStart、GuardsCheckEnd、ActivationEnd、NavigationEnd等。日誌
下面介紹刷新當前頁面的幾種方法:code
訂閱Router Event,在NavigationEnd中從新加載數據,銷燬組件時取消訂閱:component
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(); } } ... }
這種方式可按需配置要刷新的頁面,但代碼煩瑣。router
有兩種實現方式:
在代碼中更改策略:對象
constructor(private heroService: HeroService, private router: Router) { this.router.routeReuseStrategy.shouldReuseRoute = function () { return false; }; }
Angular應用Router爲單例對象,所以使用這種方式,在一個組件中更改策略後會影響其餘組件,但從瀏覽器刷新頁面後Router會從新初始化,容易形成混亂,不推薦使用。blog
自定義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} ] })
這種方式能夠實現較爲複雜的Route重用策略。
使用Resolve能夠預先從服務器上獲取數據,這樣在路由激活前數據已準備好。
將組件中的初始化代碼轉移到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}
constructor(private heroService: HeroService, private route: ActivatedRoute) { } ngOnInit() { this.route.data.subscribe((data: { heroes: Hero[] }) => { this.heroes = data.heroes; }); }
runGuardsAndResolvers可選值:'paramsChange' 、'paramsOrQueryParamsChange'、'always'
{path: 'heroes', component: HeroesComponent, canActivate: [CanActivateAuthGuard], resolve: {heroes: HeroesResolverService}, runGuardsAndResolvers: 'always'}
給Router增長時間參數:
<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廣州馬拉松