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 => {
      ...
    })
  }
}
相关推荐
yivifu30 分钟前
手搓HTML双行夹批效果
前端·html·html双行夹注
奔跑的卡卡1 小时前
Web开发与AI融合-第一篇:Web开发与AI融合的时代序幕
前端·人工智能
IT_陈寒1 小时前
Redis批量删除的大坑,差点让我加班到天亮
前端·人工智能·后端
帆张芳显1 小时前
智表ZCELL产品V3.6 版发布,新增系统预置右键菜单操作、页签栏操作等功能
前端·canva可画·excel插件
漂流瓶jz2 小时前
运行时vs编译时:CSS in JS四种主流方案介绍和对比
前端·javascript·css
Asmewill2 小时前
uv包管理命令
前端
发现一只大呆瓜2 小时前
深入浅出 Tree Shaking:Rollup 是如何“摇”掉死代码的?
前端·性能优化·vite
weixin199701080162 小时前
《转转商品详情页前端性能优化实战》
前端·性能优化
钮钴禄·爱因斯晨2 小时前
他到底喜欢我吗?赛博塔罗Java+前端实现,一键解答!
java·开发语言·前端·javascript·css·html
Watermelo6172 小时前
理解 JavaScript 中的“ / ”:路径、资源与目录、nginx配置、请求、转义的那些事
前端·javascript·vue.js·chrome·nginx·正则表达式·seo