问道Angular——Angular革新当前页面

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);
  }
}

☞☞☞问道Angular系列☜☜☜

    原文作者:staven
    原文地址: https://segmentfault.com/a/1190000017077503
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞