Angular 6 Injectable картографический сервис сбрасывается для каждого запроса - PullRequest
0 голосов
/ 07 октября 2018

У меня есть служба кэширования, которая вводится в перехватчик кэша, но карта в моей службе кэширования сбрасывается при каждом запросе.

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 { }

Кэш (CacheMapService), который вводится в CachingInterceptor, хранит запрос, но когда следующий запрос сделан, карта (cacheMap) больше не содержит значение, а размер0.

Что я делаю не так?

...