如何在角度5中执行缓存http get请求? [英] How to perform caching http get request in angular 5?

查看:71
本文介绍了如何在角度5中执行缓存http get请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { catchError } from 'rxjs/operators';

    @Injectable()
    export class ApiService {

      constructor(private http: HttpClient) { }

      // get API request
      public apiGetRequest(url: any): Observable<any> {
        return this.http.get(url)
          .pipe(
            catchError(this.handleError('apiGetRequest'))
          );
      }
    }

我将angular 5与rxjs版本5.5.6结合使用,试图缓存多个http get请求.

I am using angular 5 with rxjs version 5.5.6 I am trying to cache multiple http get request.

推荐答案

您可以创建内部键/值对存储解决方案来缓存请求. 在这里,我为此使用 Map().

You can create internal key/value pair storage solution to cache the request. Here I am using Map() for this.

import { Injectable } from '@angular/core';
import { HttpEvent, HttpRequest, HttpHandler, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap, shareReplay } from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  private cache = new Map<string, any>();

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.method !== 'GET') {
      return next.handle(request);
    }

    const cachedResponse = this.cache.get(request.url);
    if (cachedResponse) {
      return of(cachedResponse);
    }

    return next.handle(request).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          this.cache.set(request.url, event);
        }
      })
    );
  }
}

现在,您需要照顾缓存失效.每当数据更改时,您都需要使它们无效.

Now You need to take care of cache invalidation. whenever data changes you need to invalidate.

这篇关于如何在角度5中执行缓存http get请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆