简体   繁体   中英

RXJS Observable.of() as a Observable<HttpEvent<any>> in HttpInterceptor

I have an Angular's HttpInterceptor looking like that:

(...)

export class CacheInterceptor implements HttpInterceptor {

  constructor(private cache: CacheService) {}

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

   const cachedResponse = this.cache.restore(req); // Object with cached data

   return cachedResponse ?
     of(cachedResponse): this.sendRequest(req, next);

(...)
}

Generally speaking it seems to work in the end but Angular's compiler is complaining showing error about types not matching:

ERROR in cache.interceptor.ts(27,5): error TS2322: >Type 'Observable> | Observable' is not assignable to >type 'Observable>'. Type 'Observable' is not assignable to type >'Observable>'. Type 'string' is not assignable to type 'HttpEvent'.

Almost the same example can be found in the Angular Docs.

The problem here is that of(cachedResponse) is not a type Observable<HttpEvent<any>> but Observable<string> .

I tried many ways but I can't think of what would be the best solution for this. Is it possible in any way to convert cached data to Observable<HttpEvent<any>> type or possibly there is another good way of fixing it? I know I could provide my own HttpInterceptor interface with proper types for my case or even simply remove HttpInterface reference but these might not be the best solutions, especially tha latter one. Anybody?

If you cannot change the typing of CacheService , which is what your question sounds like to me, then you can just use a type assertion:

const cachedResponse = this.cache.restore(req) as HttpEvent<any>;

Note that a type assertion does not modify the data; it simply tells the Typescript compiler that you know that the type is what you claim it is.

Ideally, however, CacheService#restore is defined generically, in which case

const cachedResponse = this.cache.restore<HttpEvent<any>>(req);

would work. Functionally speaking it's exactly the same and makes no difference, but it depends on restore being appropriately typed. Since I don't know what CacheService is in your case, I can't know whether that's the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM