代码之家  ›  专栏  ›  技术社区  ›  Lansana Camara

只给出单一值的多值可观测流

  •  0
  • Lansana Camara  · 技术社区  · 6 年前

    official Angular docs ,并通过使用 startWith .

    示例代码:

    import {Injectable} from '@angular/core';
    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
    
    import {Observable} from 'rxjs';
    import {tap, startWith} from 'rxjs/operators';
    
    @Injectable()
    export class CacheInterceptor implements HttpInterceptor {
        intercept(req: HttpRequest<any>, next: HttpHandler) {
            if (req.method !== 'GET') {
                return next.handle(req);
            }
    
            const cachedResponse = cache.get(req);
            const results$ = sendRequest(req, next);
            return cachedResponse ? results$.pipe(startWith(cachedResponse)) : results$;
        }
    }
    
    function sendRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            tap(event => {
                if (event instanceof HttpResponse) {
                    cache.put(req, event);
                }
            })
        );
    }
    
    export class HttpCache {
        cache = new Map();
    
        get(req: HttpRequest<any>): HttpResponse<any> | undefined {
            const url = req.urlWithParams;
            const cached = this.cache.get(url);
    
            if (!cached) {
                return undefined;
            }
    
            return cached.response;
        }
    
        put(req: HttpRequest<any>, response: HttpResponse<any>): void {
            const url = req.urlWithParams;
            const entry = {url, response, lastRead: Date.now()};
    
            this.cache.set(url, entry);
        }
    }
    
    const cache: HttpCache = new HttpCache();
    

    . 有什么好处?

    0 回复  |  直到 6 年前