Angular刷新当前页面的实现方法
程序员文章站
2022-05-29 18:09:55
onsameurlnavigation
从angular5.1起提供onsameurlnavigation来支持路由重新加载。
有两个值'reload'和'igno...
onsameurlnavigation
从angular5.1起提供onsameurlnavigation来支持路由重新加载。
有两个值'reload'和'ignore'。默认为'ignore'
定义当路由器收到一个导航到当前 url 的请求时应该怎么做。 默认情况下,路由器将会忽略这次导航。但这样会阻止类似于 "刷新" 按钮的特性。 使用该选项可以配置导航到当前 url 时的行为。
使用
配置onsameurlnavigation
@ngmodule({ imports: [routermodule.forroot( routes, { onsameurlnavigation: 'reload' } )], exports: [routermodule] })
reload实际上不会重新加载路由,只是重新出发挂载在路由器上的事件。
配置runguardsandresolvers
runguardsandresolvers有三个值:
- paramschange: 仅在路由参数更改时触发。如/reports/:id 中id更改
- paramsorqueryparamschange: 当路由参数更改或参训参数更改时触发。如/reports/:id/list?page=23中的id或page属性更改
- always :始终触发
const routes: routes = [ { path: '', children: [ { path: 'report-list', component: reportlistcomponent }, { path: 'detail/:id', component: reportdetailcomponent, runguardsandresolvers: 'always' }, { path: '', redirectto: 'report-list', pathmatch: 'full' } ] } ];
组件监听router.events
import {component, ondestroy, oninit} from '@angular/core'; import {observable} from 'rxjs'; import {report} from '@models/report'; import {reportservice} from '@services/report.service'; import {activatedroute, navigationend, router} from '@angular/router'; @component({ selector: 'app-report-detail', templateurl: './report-detail.component.html', styleurls: ['./report-detail.component.scss'] }) export class reportdetailcomponent implements oninit, ondestroy { report$: observable<report>; navigationsubscription; constructor( private reportservice: reportservice, private router: router, private route: activatedroute ) { this.navigationsubscription = this.router.events.subscribe((event: any) => { if (event instanceof navigationend) { this.initload(event); } }); } ngoninit() { const id = +this.route.snapshot.parammap.get('id'); this.report$ = this.reportservice.getreport(id); } ngondestroy(): void { // 销毁navigationsubscription,避免内存泄漏 if (this.navigationsubscription) { this.navigationsubscription.unsubscribe(); } } initload(e) { window.scrollto(0, 0); console.log(e); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。