可观察的流,它将发出两次值

时间:2019-02-16 19:17:03

标签: angular typescript rxjs

我有一个需要观察到的值来发出两个值的情况。应该立即发出第一个值,并且所有订户应立即获得该值。第二个值可能需要一些时间,但所有订户也应获得该值。

目前,我是这样做的:

import {Observable} from 'rxjs';
import {tap, startWith} from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        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 {
        // ...
    }

    put(req: HttpRequest<any>, response: HttpResponse<any>): void {
        // ...
    }
}

const cache: HttpCache = new HttpCache();

如您所见,我尝试做results$.pipe(startWith(cachedResponse))

似乎发生的事情是我总是发出results$值,而从未发出cachedResponse值。任何帮助将不胜感激。

0 个答案:

没有答案