<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等。
onSameUrlNavigation和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(); } } ... }
onSameUrlNavigation和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,exports: [RouterModule],providers: [ {provide: RouteReuseStrategy,useClass: CustomreuseStrategy} ] })
这种方式可以实现较为复杂的Route重用策略。
onSameUrlNavigation和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}
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‘,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()} }); }
constructor(private heroService: HeroService,private route: ActivatedRoute) { this.route.queryParamMap.subscribe(params => { if (params.get(‘refresh‘)) { this.init(); } }); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。