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 => {
      ...
    })
  }
}
相关推荐
UXbot15 分钟前
原型设计工具如何帮助新人快速进入产品行业?
前端·低代码·ui·交互·团队开发·原型模式·web app
黄敬峰1 小时前
从 DFS 遍历到抖音推荐算法:前端工程师的硬核复习笔记
前端
zach1 小时前
网页中的虚拟滚动技术是不是源自IOS中的tableview的机制
前端
林希_Rachel_傻希希1 小时前
1小时速通React之Hooks
前端·javascript·面试
柯克七七1 小时前
公司前端项目打包体积从 2MB 降到 400KB,我改了这四个配置
前端
英勇无比的消炎药1 小时前
我才发现这些架构的“拆”与“合”哲学
前端
shen_1 小时前
AI Coding:前端UI规范笔记
前端
llz_1122 小时前
web-第五次课后作业
前端·后端·http
恋猫de小郭3 小时前
Redis 作者反驳「中国模型之所以强,是因为通过 API 蒸馏了美国模型」
前端·人工智能·ai编程