当前位置:   article > 正文

前端 获取API的响应时间 的方法总结_前端 计算接口时间的方法

前端 计算接口时间的方法

进入正文之前需要了解的概念:

  • API请求时间:指从发送API请求到接收到响应所经过的时间。
  • 网络延迟:指数据从发送端到接收端所需的时间,受网络质量和距离等因素影响。
  • 服务器处理时间:指服务器处理请求所需的时间,包括数据库查询、计算等操作。
  • 数据传输时间:指数据在网络中传输所需的时间,受网络带宽和数据量等因素影响。

前端获取API响应时间的方法有多种途径,以下是其中三种常见的方法:

  1. Performance API:使用浏览器提供的Performance API可以获取到页面加载和执行的性能数据,包括API请求的响应时间。可以通过以下代码来获取API请求的响应时间:
    1. const startTime = performance.now();
    2. fetch('https://api.example.com/data')
    3.   .then(response => {
    4.     const endTime = performance.now();
    5.     const responseTime = endTime - startTime;
    6.     console.log('API响应时间:', responseTime);
    7.     return response.json();
    8.   })
    9.   .then(data => {
    10.     // 处理API响应数据
    11.   });
  2. XHR对象:通过XMLHttpRequest对象发送API请求,并在请求完成时计算响应时间。以下是一个简单的示例:
    1. const xhr = new XMLHttpRequest();
    2. const startTime = new Date().getTime();
    3. xhr.open('GET', 'https://api.example.com/data', true);
    4. xhr.onreadystatechange = function() {
    5.   if (xhr.readyState === 4 && xhr.status === 200) {
    6.     const endTime = new Date().getTime();
    7.     const responseTime = endTime - startTime;
    8.     console.log('API响应时间:', responseTime);
    9.     // 处理API响应数据
    10.   }
    11. };
    12. xhr.send();
  3. Fetch API:使用Fetch API发送API请求,并在Promise链中计算响应时间。以下是一个示例:
    1. const startTime = new Date().getTime();
    2. fetch('https://api.example.com/data')
    3.   .then(response => {
    4.     const endTime = new Date().getTime();
    5.     const responseTime = endTime - startTime;
    6.     console.log('API响应时间:', responseTime);
    7.     return response.json();
    8.   })
    9.   .then(data => {
    10.     // 处理API响应数据
    11.   });

如果是针对于Angular,我们可以优化成下面的方法和采用其它新的方法:

  1. HttpInterceptor拦截器:使用HttpInterceptor拦截器可以在每个HTTP请求和响应时执行一些操作,包括计算API响应时间。以下是一个简单的示例:
    1. import { Injectable } from '@angular/core';
    2. import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    3. import { Observable } from 'rxjs';
    4. import { tap } from 'rxjs/operators';
    5. @Injectable()
    6. export class TimingInterceptor implements HttpInterceptor {
    7.   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    8.     const startTime = new Date().getTime();
    9.     return next.handle(req).pipe(
    10.       tap(() => {
    11.         const endTime = new Date().getTime();
    12.         const responseTime = endTime - startTime;
    13.         console.log('API响应时间:', responseTime);
    14.       })
    15.     );
    16.   }
    17. }
  2. Http请求拦截:在Angular中可以通过拦截Http请求来计算API的响应时间。以下是一个示例:
    1. import { Injectable } from '@angular/core';
    2. import { HttpClient, HttpRequest } from '@angular/common/http';
    3. @Injectable()
    4. export class ApiService {
    5.   constructor(private http: HttpClient) {}
    6.   getWithTiming(url: string) {
    7.     const startTime = new Date().getTime();
    8.     return this.http.get(url).pipe(
    9.       finalize(() => {
    10.         const endTime = new Date().getTime();
    11.         const responseTime = endTime - startTime;
    12.         console.log('API响应时间:', responseTime);
    13.       })
    14.     );
    15.   }
    16. }
  3. RxJS操作符:使用RxJS操作符可以在Observable流中计算API的响应时间。以下是一个示例:
    1. import { HttpClient } from '@angular/common/http';
    2. import { map } from 'rxjs/operators';
    3. constructor(private http: HttpClient) {}
    4. getWithTiming(url: string) {
    5.   const startTime = new Date().getTime();
    6.   return this.http.get(url).pipe(
    7.     map(response => {
    8.       const endTime = new Date().getTime();
    9.       const responseTime = endTime - startTime;
    10.       console.log('API响应时间:', responseTime);
    11.       return response;
    12.     })
    13.   );
    14. }
  4. Angular Performance API:Angular提供了Performance API来获取应用程序性能数据,可以通过以下代码获取API响应时间:
    1. import { ApplicationRef } from '@angular/core';
    2. constructor(private appRef: ApplicationRef) {}
    3. ngAfterViewInit() {
    4.   const startTime = performance.now();
    5.   this.http.get('https://api.example.com/data').subscribe(() => {
    6.     const endTime = performance.now();
    7.     const responseTime = endTime - startTime;
    8.     console.log('API响应时间:', responseTime);
    9.     this.appRef.tick();
    10.   });
    11. }
  5. Angular HttpClient拦截器和Performance API结合:结合使用HttpClient拦截器和Performance API可以更精确地获取API响应时间。
    1. import { Injectable } from '@angular/core';
    2. import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    3. import { Observable } from 'rxjs';
    4. @Injectable()
    5. export class TimingInterceptor implements HttpInterceptor {
    6.   constructor(private appRef: ApplicationRef) {}
    7.   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    8.     const startTime = performance.now();
    9.     return next.handle(req).pipe(
    10.       finalize(() => {
    11.         const endTime = performance.now();
    12.         const responseTime = endTime - startTime;
    13.         console.log('API响应时间:', responseTime);
    14.         this.appRef.tick();
    15.       })
    16.     );
    17.   }
    18. }

拓展:

        对于Angular有些小伙伴肯定有听说过,timeout 和timeoutWith方法,下面是这两个方法与上面的方法区别和使用介绍:

   timeout 用于处理 Observable 的超时情况,而 timeoutWith 则用于在超时时切换到备用的 Observable。如果你想要处理 Observable 的超时情况并执行特定的操作,可以使用 timeout 方法;如果你想要在超时时切换到备用的 Observable 进行替代操作,可以使用 timeoutWith 方法。

timeoutWith 方法

  • timeoutWith 方法也用于在 Observable 发出数据的时间超过指定时间后,但它允许你提供一个备用的 Observable,用于替代超时的情况。
  • 如果超时,将终止原始 Observable 并开始订阅备用 Observable。
  • 示例代码:
    1. import { of, timer } from 'rxjs';
    2. import { timeoutWith, switchMap } from 'rxjs/operators';
    3. const source = of('Hello').pipe(
    4. switchMap(value => timer(1000).pipe(timeoutWith(500, of('World')))) // 1秒后超时,切换到备用 Observable
    5. );
    6. source.subscribe(value => console.log('Value:', value)); // 输出:Value: World

timeout 方法

  • timeout 方法用于在 Observable 发出数据的时间超过指定时间后,将 Observable 中的数据流终止,并抛出一个错误。
  • 该方法通常用于处理异步操作超时的情况,比如等待服务器响应超时等。
  • 示例代码:
    1. import { of } from 'rxjs';
    2. import { timeout } from 'rxjs/operators';
    3. const source = of('Hello').pipe(timeout(3000)); // 3秒后超时
    4. source.subscribe(
    5. value => console.log('Value:', value),
    6. error => console.error('Error:', error) // 如果超时会抛出 TimeoutError
    7. );
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/987077
推荐阅读
相关标签
  

闽ICP备14008679号