如何将CacheInterceptor最后修改为Cache

时间:2018-03-08 17:32:11

标签: angular typescript

我在Angular 5.2中实现了this一个很好的Cache Interceptor示例。到目前为止它的效果非常好。但是,我想修改此缓存,以便只从缓存加载最后3秒的查询,应重新请求旧版本。我怎样才能做到这一点?

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

import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
    private cache: { [name: string]: AsyncSubject<HttpEvent<any>> } = {};

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (request.method !== 'GET') {
            return next.handle(request);
        }
        const cachedResponse = this.cache[request.urlWithParams] || null;
        if (cachedResponse) {
            return cachedResponse
        }
        const subject = this.cache[request.urlWithParams] = new AsyncSubject<HttpEvent<any>>();
        next.handle(request).do(event => {
            if (event instanceof HttpResponse) {
                subject.next(event);
                subject.complete();
            }
        }).subscribe(); // must subscribe to actually kick off request!
        return subject;
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个 - 只计算timediff:

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

import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
    private cache: { [name: string]: AsyncSubject<HttpEvent<any>> } = {};
    private prevTimeStamp: any = new Date();
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (request.method !== 'GET') {
            return next.handle(request);
        }
        const currentTimeStamp = new Date();
        const cachedResponse = this.cache[request.urlWithParams] || null;
         const diff = (currentTimeStamp - this.prevTimeStamp) / 1000;
        if (cachedResponse & (diff > 3)) {
            return cachedResponse
        }
        this.prevTimeStamp = currentTimeStamp;
        const subject = this.cache[request.urlWithParams] = new AsyncSubject<HttpEvent<any>>();
        next.handle(request).do(event => {
            if (event instanceof HttpResponse) {
                subject.next(event);
                subject.complete();
            }
        }).subscribe(); // must subscribe to actually kick off request!
        return subject;
    }
}

答案 1 :(得分:0)

非常感谢使用它的解决方案,我设法开发了自己的解决方案。 5秒后缓存的对象被删除,另外在DELETE或POST之后,因为我认为某些内容已经发生了变化。也许它对任何人都有帮助。我没有长时间编程Angular,或者如果有人发现我的方法有错误,我很感激反馈。

match_parent