当前位置: 首页 > Web前端 > HTML5

为Angular服务器端渲染的应用程序设置渲染超时

时间:2023-04-05 20:45:05 HTML5

我们使用setTimeout来模拟需要5秒才能完成的API:constexpress=require('express');constapp=express();app.get('/api/fast',(req,res)=>{console.log('fastendpointhit');res.send({response:'fast'});});app.get('/api/slow',(req,res)=>{setTimeout(()=>{console.log('slowendpointhit');res.send({response:'slow'});},5000);});app.listen(8081,()=>{console.log('Listening');});然后创建一个新的Angular服务并调用这个/api/slow:import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';import{Observable}from'rxjs';@Injectable({providedIn:'root'})exportclassCustomService{constructor(privatehttp:HttpClient){}publicgetFast():Observable{returnthis.http.get('http://localhost:8081/api/快速');}publicgetSlow():Observable{returnthis.http.get('http://localhost:8081/api/slow');}}服务端渲染模式,等待本次API调用返回如果至少需要5秒,我们可以为这个API调用设置一个超时机制。如果服务器端渲染超过了我们指定的超时间隔而没有得到API响应,我们就放弃API调用并让它在客户端渲染模式下继续。我们使用RouteResolver来实现这一点。从Angular路由框架导入路由器:import{Resolve}from'@angular/router';从Angular通用开发工具包导入Angular运行时环境监控API:import{isPlatformBrowser}from'@angular/common';导入注入令牌以获取当前运行平台ID:从“@angular/core”导入{Injectable,Inject,PLATFORM_ID};创建一个新的服务类:import{Injectable,Inject,PLATFORM_ID}from'@angular/core';从'@angular/router'导入{Resolve};从'rxjs'导入{Observable,timer};从'@angular/common'导入{isPlatformBrowser};从'./custom.service'导入{CustomService};导入{takeUntil}来自'rxjs/operators';@Injectable({providedIn:'root'})exportclassSlowComponentResolverServiceimplementsResolve{constructor(privateservice:CustomService,@Inject(PLATFORM_ID)privateplatformId:any){}publicresolve():Observable{if(isPlatformBrowser(this.platformId)){returnthis.service.getSlow();如果当前应用运行在浏览器端,则返回上图中的isPlatformBrowser(this.platformId)是的,所以直接调用慢API。否则创建一个在500毫秒后发出值的Observable:constwatchdog:Observable=timer(500);我们将这个watchDogObservable管道传输到this.service.getSlow的下游这样,如果this.service.getSlow()返回的Observable在500毫秒内没有发出值,watchdog将向Component推送一个空值,否则,API的真正响应将被推送到Component.我们需要更新应用相关的路由代码来消费这个Resolver。为slowComponent分配解析器:constroutes:Routes=[{path:'',redirectTo:'fast',pathMatch:'full'},{path:'fast',component:FastComponent},{path:'slow',组件:SlowComponent,解析:{响应:SlowComponentResolverService}}];在slowComponent的实现代码中,从指定的Routeresolver读取API响应数据:import{Component}from'@angular/core';import{ActivatedRoute}from'@angular/router';@Component({selector:'app-slow',template:`

Responseis:{{response|json}}

`,styles:[]})exportclassSlowComponent{publicresponse:any=this.router.snapshot.data.response;constructor(privaterouter:ActivatedRoute){}}注意这里没有直接访问RouteResolver:this.router.snapshot.data.response当API在500毫秒内返回时,所有的slowComponent源码都是由服务端生成的:当API在500毫秒内没有返回数据,客户端会重新调用API,然后在客户端完成渲染: