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 => {
      ...
    })
  }
}
相关推荐
右耳朵猫AI2 分钟前
Web前端周刊2026W36 | pnpm 12 Rust 重写、Remix 3 RC、Node.js 26.8.0、htmx 4.0 大版本
前端·rust·node.js
平头哥~17 分钟前
Day 21 | animation 与 keyframes:把动画从 A 到 B 变成多点编排
前端·css·css3·css学习
宿67410 小时前
vue3-包管理器
前端·vue.js
@PHARAOH10 小时前
WHAT - Remix 入门和基本实践:理解两套产物
前端·remix
mayaairi10 小时前
Vue2 生命周期完全指南:从创建到销毁的8个钩子函数
前端·javascript·vue.js
xy345311 小时前
axure9.0 如何打造一个计时器(简单版)
前端·ui·html·axure·原型·产品设计
IMPYLH12 小时前
HTML 的 <pre> 元素
前端·javascript·html
tsumikistep13 小时前
【前端】Vue + Axios 跨域问题实战:7070 代理转发 8080 + 401 报错分析(黑马外卖)
前端·javascript·vue.js
lichenyang45313 小时前
鸿蒙首页从等高商品 Grid 到双列瀑布流:同一张图也能做出小红书式浏览节奏
前端
里欧跑得慢13 小时前
Flutter主题与样式详解
前端·css·flutter·web