进入正文之前需要了解的概念:
前端获取API响应时间的方法有多种途径,以下是其中三种常见的方法:
- const startTime = performance.now();
- fetch('https://api.example.com/data')
- .then(response => {
- const endTime = performance.now();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- return response.json();
- })
- .then(data => {
- // 处理API响应数据
- });
- const xhr = new XMLHttpRequest();
- const startTime = new Date().getTime();
- xhr.open('GET', 'https://api.example.com/data', true);
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4 && xhr.status === 200) {
- const endTime = new Date().getTime();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- // 处理API响应数据
- }
- };
- xhr.send();
- const startTime = new Date().getTime();
- fetch('https://api.example.com/data')
- .then(response => {
- const endTime = new Date().getTime();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- return response.json();
- })
- .then(data => {
- // 处理API响应数据
- });
如果是针对于Angular,我们可以优化成下面的方法和采用其它新的方法:
- import { Injectable } from '@angular/core';
- import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
- import { Observable } from 'rxjs';
- import { tap } from 'rxjs/operators';
-
- @Injectable()
- export class TimingInterceptor implements HttpInterceptor {
- intercept(req: HttpRequest
, next: HttpHandler): Observable<HttpEvent> { - const startTime = new Date().getTime();
- return next.handle(req).pipe(
- tap(() => {
- const endTime = new Date().getTime();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- })
- );
- }
- }
- import { Injectable } from '@angular/core';
- import { HttpClient, HttpRequest } from '@angular/common/http';
-
- @Injectable()
- export class ApiService {
- constructor(private http: HttpClient) {}
-
- getWithTiming(url: string) {
- const startTime = new Date().getTime();
- return this.http.get(url).pipe(
- finalize(() => {
- const endTime = new Date().getTime();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- })
- );
- }
- }
- import { HttpClient } from '@angular/common/http';
- import { map } from 'rxjs/operators';
-
- constructor(private http: HttpClient) {}
-
- getWithTiming(url: string) {
- const startTime = new Date().getTime();
- return this.http.get(url).pipe(
- map(response => {
- const endTime = new Date().getTime();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- return response;
- })
- );
- }
- import { ApplicationRef } from '@angular/core';
-
- constructor(private appRef: ApplicationRef) {}
-
- ngAfterViewInit() {
- const startTime = performance.now();
- this.http.get('https://api.example.com/data').subscribe(() => {
- const endTime = performance.now();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- this.appRef.tick();
- });
- }
- import { Injectable } from '@angular/core';
- import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
- import { Observable } from 'rxjs';
-
- @Injectable()
- export class TimingInterceptor implements HttpInterceptor {
- constructor(private appRef: ApplicationRef) {}
-
- intercept(req: HttpRequest
, next: HttpHandler): Observable<HttpEvent> { - const startTime = performance.now();
- return next.handle(req).pipe(
- finalize(() => {
- const endTime = performance.now();
- const responseTime = endTime - startTime;
- console.log('API响应时间:', responseTime);
- this.appRef.tick();
- })
- );
- }
- }
拓展:
对于Angular有些小伙伴肯定有听说过,timeout 和timeoutWith方法,下面是这两个方法与上面的方法区别和使用介绍:
timeout
用于处理 Observable 的超时情况,而 timeoutWith
则用于在超时时切换到备用的 Observable。如果你想要处理 Observable 的超时情况并执行特定的操作,可以使用 timeout
方法;如果你想要在超时时切换到备用的 Observable 进行替代操作,可以使用 timeoutWith
方法。
timeoutWith
方法:
timeoutWith
方法也用于在 Observable 发出数据的时间超过指定时间后,但它允许你提供一个备用的 Observable,用于替代超时的情况。- import { of, timer } from 'rxjs';
- import { timeoutWith, switchMap } from 'rxjs/operators';
-
- const source = of('Hello').pipe(
- switchMap(value => timer(1000).pipe(timeoutWith(500, of('World')))) // 1秒后超时,切换到备用 Observable
- );
-
- source.subscribe(value => console.log('Value:', value)); // 输出:Value: World
timeout
方法:
timeout
方法用于在 Observable 发出数据的时间超过指定时间后,将 Observable 中的数据流终止,并抛出一个错误。- import { of } from 'rxjs';
- import { timeout } from 'rxjs/operators';
-
- const source = of('Hello').pipe(timeout(3000)); // 3秒后超时
- source.subscribe(
- value => console.log('Value:', value),
- error => console.error('Error:', error) // 如果超时会抛出 TimeoutError
- );