默认,当收到导航到当前URL的请求,Angular路由器会忽略。
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
重复点击同一链接页面不会刷新。
从Angular 5.1起提供onSameUrlNavigation属性,支持重新加载路由。
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule]
})
onSameUrlNavigation有两个可选值:'reload'和'ignore',默认为'ignore'。但仅将onSameUrlNavigation改为'reload',只会触发RouterEvent事件,页面是不会重新加载的,还需配合其它方法。在继续之前,我们启用Router Trace,从浏览器控制台查看一下路由事件日志:
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload', enableTracing: true})],
exports: [RouterModule]
})
可以看到,未配置onSameUrlNavigation时,再次点击同一链接不会输出日志,配置onSameUrlNavigation为'reload'后,会输出日志,其中包含的事件有:NavigationStart、RoutesRecognized、GuardsCheckStart、GuardsCheckEnd、ActivationEnd、NavigationEnd等。
下面介绍刷新当前页面的几种方法:
NavigationEnd
- 配置onSameUrlNavigation为'reload'
- 监听NavigationEnd事件
订阅Router Event,在NavigationEnd中重新加载数据,销毁组件时取消订阅:
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
- 配置onSameUrlNavigation为'reload'
- 自定义RouteReuseStrategy,不重用Route
有两种实现方式: 在代码中更改策略:
constructor(private heroService: HeroService, private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
Angular应用Router为单例对象,因此使用这种方式,在一个组件中更改策略后会影响其他组件,但从浏览器刷新页面后Router会重新初始化,容易造成混乱,不推荐使用。
自定义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可以预先从服务器上获取数据,这样在路由激活前数据已准备好。
- 实现ResolverService
将组件中的初始化代码转移到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}
- 修改组件代码,改为从resolve中获取数据
constructor(private heroService: HeroService, private route: ActivatedRoute) {
}
ngOnInit() {
this.route.data.subscribe((data: { heroes: Hero[] }) => {
this.heroes = data.heroes;
});
}
- 配置onSameUrlNavigation为'reload'
- 配置runGuardsAndResolvers为‘always’
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广州马拉松