Angular: resolve 守卫

resolve 守卫的作用

  1. 在使用真实API时,很有可能因为数据返回有延迟,导致无法及时显示,也就是空白页面。
    所以期望等所有数据都准备好了,才渲染路由组件,这就需要 Resolve 守卫,导航前预先加载路由信息
  2. 当路由切换的时候,被路由的页面中的元素(标签)就会立马显示出来,同时,数据会被准备好并呈现出来。但是注意,数据和元素并不是同步的,在没有任何设置的情况下,AngularJS默认先呈现出元素,而后再呈现出数据。这样就会导致页面会被渲染两遍,导致"页面UI抖动"的问题,对用户不太友好。resolve的出现解决了这个问题。

resolve 的使用

resolve属性里的值会在路由成功前被预先设定好,然后注入到控制器中。

就是等数据都"就位"后,才进行路由(其实也不能叫路由,因为路由是一些列的操作,其中就包括了设置resolve属性等等)。

这样的好处就是页面仅会被渲染一遍。

sheetInfo.resolve.ts

typescript 复制代码
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { SheetService } from '../../services/sheet.service';

@Injectable()
export class SheetInfoResolverService implements Resolve<SongSheet> {
  constructor(private sheetServe: SheetService) {}
  resolve(route: ActivatedRouteSnapshot): Observable<SongSheet> {
    return this.sheetServe.getSongSheetDetail(Number(route.paramMap.get('id')));
  }
}

sheetInfo-routing.module.ts

typescript 复制代码
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [{
  path: 'sheetInfo/:id',
  component: SheetInfoComponent,
  data: {
    title: '歌单详情'
  },
  resolve: {
    sheetInfo: SheetInfoResolverService
  }
}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: [SheetInfoResolverService]
})
export class SheetInfoRoutingModule { }

sheetInfo.component.ts

typescript 复制代码
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs/internal/operators';

export class SheetInfoComponent implements OnInit {
  constructor(
    private route: ActivatedRoute
  ) { 
    this.route.data.pipe(map(res => res.sheetInfo)).subscribe(res => {
      ...
    })
  }
}
相关推荐
曼巴UE55 小时前
UE FString, FName ,FText 三者转换,再次学习,官方文档理解
服务器·前端·javascript
行走的陀螺仪6 小时前
高级前端 Input 公共组件设计方案(Vue3 + TypeScript)
前端·javascript·typescript·vue·组件设计方案
一颗不甘坠落的流星7 小时前
【Antd】基于 Upload 组件,导入Json文件并转换为Json数据
前端·javascript·json
LYFlied7 小时前
Vue2 与 Vue3 虚拟DOM更新原理深度解析
前端·javascript·vue.js·虚拟dom
Lucky_Turtle7 小时前
【Node】npm install报错npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
小飞侠在吗7 小时前
vue shallowRef 与 shallowReacitive
前端·javascript·vue.js
惜分飞8 小时前
sql server 事务日志备份异常恢复案例---惜分飞
前端·数据库·php
GISer_Jing8 小时前
WebGL实例化渲染:性能提升策略
前端·javascript·webgl
烟锁池塘柳08 小时前
【技术栈-前端】告别“转圈圈”:详解前端性能优化之“乐观 UI” (Optimistic UI)
前端·ui