经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » AngularJS » 查看文章
JS Angular 服务器端渲染应用设置渲染超时时间
来源:jb51  时间:2022/6/27 10:53:26  对本文有异议

我们用 setTimeout 模拟一个需要 5 秒钟才能完成调用的 API:

  1. const express = require('express');
  2. const app = express();
  3. app.get('/api/fast', (req, res) => {
  4.   console.log('fast endpoint hit');
  5.   res.send({response: 'fast'});
  6. });
  7. app.get('/api/slow', (req, res) => {
  8.   setTimeout(() => {
  9.       console.log('slow endpoint hit');
  10.       res.send({response: 'slow'});
  11.   }, 5000);
  12. });
  13. app.listen(8081, () => {
  14.   console.log('Listening');
  15. });

然后新建一个 Angular service,调用这个 /api/slow:

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. @Injectable({
  5.  providedIn: 'root'
  6. })
  7. export class CustomService {
  8.  constructor(private http: HttpClient) {}
  9.  public getFast(): Observable<any> {
  10.    return this.http.get<any>('http://localhost:8081/api/fast');
  11.  }
  12.  public getSlow(): Observable<any> {
  13.    return this.http.get<any>('http://localhost:8081/api/slow');
  14.  }
  15. }

在服务器端渲染模式下,等待这个 API 调用的返回,至少需要花费 5 秒钟。我们可以给这个 API 调用设置一个超时机制。如果服务器端渲染时超过我们指定的超时间隔,还没有得到 API 响应,我们就放弃这次 API 调用,让其在客户端渲染模式下继续进行。

我们使用 RouteResolver 来实现。

从 Angular route 框架导入 router

  1. import { Resolve } from '@angular/router';

从 Angular common 开发包导入 Angular 运行环境监测的 API:

  1. import { isPlatformBrowser } from '@angular/common';

导入 injection token,获得当前运行的 platform id:

  1. import { Injectable, Inject, PLATFORM_ID } from '@angular/core';

新建一个 service class:

  1. import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
  2. import { Resolve } from '@angular/router';
  3. import { Observable, timer } from 'rxjs';
  4. import { isPlatformBrowser } from '@angular/common';
  5. import { CustomService } from './custom.service';
  6. import { takeUntil } from 'rxjs/operators';
  7. @Injectable({
  8.  providedIn: 'root'
  9. })
  10. export class SlowComponentResolverService implements Resolve<any> {
  11.  constructor(private service: CustomService, @Inject(PLATFORM_ID) private platformId: any) { }
  12.  public resolve(): Observable<any> {
  13.    if (isPlatformBrowser(this.platformId)) {
  14.      return this.service.getSlow();
  15.    }

如果当前应用运行于浏览器端,上图的 isPlatformBrowser(this.platformId) 返回 true,因此直接调用慢速 API.

否则创建一个 Observable,500 毫秒后发射值:

  1. const watchdog: Observable<number> = timer(500);

我们将这个 watchDog Observable 通过 pipe 设置到 this.service.getSlow 的下游。这样,如果 this.service.getSlow() 返回的 Observable 在 500 毫秒之内不 emit 值的话,watchdog 就会向 Component push null 值,否则,API 的真实 response 会推送给 Component.

我们需要更新应用相关的 routing 代码来消费这个 Resolver.

给 slowComponent 分配一个 resolver:

  1. const routes: Routes = [
  2. {path: '', redirectTo: 'fast', pathMatch: 'full'},
  3. {path: 'fast', component: FastComponent},
  4. {path: 'slow', component: SlowComponent, resolve: {response: SlowComponentResolverService}}
  5. ];

在 slowComponent 的实现代码里,从分配的 Route resolver 里读取 API response 数据:

  1. import { Component } from '@angular/core';
  2. import { ActivatedRoute } from '@angular/router';
  3. @Component({
  4. selector: 'app-slow',
  5. template: `
  6.   <p>
  7.     Response is: {{response | json}}
  8.   </p>
  9. `,
  10. styles: []
  11. })
  12. export class SlowComponent {
  13.  
  14. public response: any = this.router.snapshot.data.response;
  15. constructor(private router: ActivatedRoute) {}
  16. }

注意这里并没有直接访问 Route Resolver:this.router.snapshot.data.response

当 API 在 500 毫秒之内返回时,所有的 slowComponent 源代码都由服务器端生成:

当 API 500 毫秒未能成功返回数据,则客户端会再次调用该 API,然后在客户端完成渲染:

到此这篇关于JS Angular 服务器端渲染应用设置渲染超时时间的文章就介绍到这了,更多相关JS Angular 服务器端渲染内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号