Angular 发起了两次 http 请求
创始人
2024-10-19 00:00:15
0

解决Angular发起两次http请求的问题,可以考虑以下方法:

  1. 检查代码中是否有重复的http请求代码。确保在需要发起http请求的地方只调用一次,避免重复发送请求。

  2. 使用缓存机制。可以使用RxJS的shareReplay操作符来缓存http请求的响应数据,避免重复发送相同的请求。例如:

import { HttpClient } from '@angular/common/http';
import { shareReplay } from 'rxjs/operators';

@Injectable()
export class DataService {
  private data$: Observable;

  constructor(private http: HttpClient) { }

  getData(): Observable {
    if (!this.data$) {
      this.data$ = this.http.get('api/data').pipe(
        shareReplay(1)
      );
    }
    return this.data$;
  }
}

在上述代码中,shareReplay(1)操作符会缓存http请求的响应数据,并在下次调用getData()时直接返回缓存的数据。

  1. 使用Angular的拦截器。可以创建一个拦截器,在拦截器中检查是否已经发起了相同的http请求,如果已经发起了,则取消当前请求。例如:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class DuplicateRequestInterceptor implements HttpInterceptor {
  private pendingRequests: Set = new Set();

  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    const key = this.getKey(req);
    if (this.pendingRequests.has(key)) {
      console.log('Duplicate request detected, canceling...');
      return Observable.empty();
    }

    this.pendingRequests.add(key);
    return next.handle(req).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            this.pendingRequests.delete(key);
          }
        },
        error => {
          this.pendingRequests.delete(key);
        }
      )
    );
  }

  private getKey(req: HttpRequest): string {
    const url = req.urlWithParams;
    const method = req.method;
    return `${method}-${url}`;
  }
}

然后,在app.module.ts中将拦截器添加到provide的providers数组中:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { DuplicateRequestInterceptor } from './duplicate-request.interceptor';

@NgModule({
  imports: [
    // ...
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: DuplicateRequestInterceptor,
      multi: true
    }
  ]
})
export class AppModule { }

通过以上方法,可以避免Angular发起重复的http请求。

相关内容

热门资讯

8分钟插件!微乐小程序黑科技,... 8分钟插件!微乐小程序黑科技,微信小程序游戏破解微乐辅助(开挂)切实真的是有挂(2026)1、微乐小...
黑科技辅助挂!微乐小程序免费黑... 黑科技辅助挂!微乐小程序免费黑科技,微乐江苏自建房辅助app(透视)都是有挂(哔哩哔哩)1、实时微乐...
第1分钟安装!微乐小程序黑科技... 第1分钟安装!微乐小程序黑科技,微乐陕西小程序辅助(开挂)果然真的有挂(2026)微乐小程序黑科技能...
2026版规律!微乐小程序黑科... 2026版规律!微乐小程序黑科技,微乐南昌辅助神器(透视)一贯有挂(哔哩哔哩)1、微乐南昌辅助神器破...
第7分钟透视!微乐小程序免费黑... 第7分钟透视!微乐小程序免费黑科技,微乐自建房插件如何安装(开挂)果然有挂(2026)1、第7分钟透...
据了解!微乐小程序免费黑科技,... 据了解!微乐小程序免费黑科技,陕西微乐小程序攻略(透视)切实真的有挂(哔哩哔哩)1、不需要AI权限,...
一分钟神器!微乐小程序黑科技,... 一分钟神器!微乐小程序黑科技,微乐小程序辅助开发(开挂)好像存在有挂(2026)1、微乐小程序黑科技...
做出回应!微乐小程序黑科技,微... 做出回应!微乐小程序黑科技,微乐自建房免费黑科技推荐(透视)竟然是真的挂(哔哩哔哩)1、任何微乐自建...
5分钟开挂!微乐小程序免费黑科... 5分钟开挂!微乐小程序免费黑科技,微乐家乡app下载(开挂)好像有挂(2026)1、该软件可以轻松地...
透视玄学!微乐小程序黑科技,微... 透视玄学!微乐小程序黑科技,微信小程序微乐破解器(透视)确实存在有挂(哔哩哔哩)1、微信小程序微乐破...