为每个请求重置Angular 6注射地图服务

时间:2018-10-07 12:19:06

标签: caching angular6 angular-http-interceptors

我有一个缓存服务,该服务被注入到缓存拦截器中,但是我的缓存服务中的映射针对每个请求都被重置。

caching-interceptor.ts

const CACHEABLE_URL = "/api/companies";

@Injectable()
export class CachingInterceptor implements HttpInterceptor {

  constructor(private cache: CacheMapService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    if (!this.isRequestCachable(req)) {
      return next.handle(req);
    }

    const cachedResponse = this.cache.get(req);

    if (cachedResponse !== null) {
      return of(cachedResponse);
    }

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

  }

  private isRequestCachable(req: HttpRequest<any>) {
    return (req.method === 'GET') && (req.url.indexOf(CACHEABLE_URL) > -1);
  }

}

cache-map.service.ts

@Injectable()
export class CacheMapService implements Cache  {

  cacheMap = new Map<string, CacheEntry>();

  get(req: HttpRequest<any>): HttpResponse<any> | null {
    const entry = this.cacheMap.get(req.urlWithParams);
    if (!entry) {
      return null;
    }
    const isExpired = (Date.now() - entry.entryTime) > CACHE_TTL;
    return isExpired ? null : entry.response;
  }

  put(req: HttpRequest<any>, res: HttpResponse<any>): void {
    const entry: CacheEntry = { url: req.urlWithParams, response: res, entryTime: Date.now() };
    this.cacheMap.set(req.urlWithParams, entry);
    this.deleteExpiredCache();
  }

  private deleteExpiredCache() {
    this.cacheMap.forEach(entry => {
      if ((Date.now() - entry.entryTime) > CACHE_TTL) {
        this.cacheMap.delete(entry.url);
      }
    })
  }

}

index.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }
];

app.module.ts

@NgModule({
  imports: [
...
  ],
  providers: [
        httpInterceptorProviders,
        CacheMapService,
        { provide: Cache, useClass: CacheMapService }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

注入到CachingInterceptor中的缓存(CacheMapService)正在存储请求,但是当下一个请求发出时,地图(cacheMap)不再保存该值,并且大小为0。

我在做什么错了?

0 个答案:

没有答案