简体   繁体   中英

Angular HTTP Client Interceptor not working when returning custom Observable

FYI This issue is related to Angular Universal

I am currently trying to create an HttpClient Interceptor that caches GET requests and returns the cached response as an observable.

I tried following the guide set by Angular interceptors here https://github.com/angular/angular/blob/master/aio/content/guide/http.md but I can't seem to get it working, when I return an Observable other than next.handle() the subscription just doesn't get triggered.

Here is a plunker demoing it not working. https://plnkr.co/edit/QzVpuIoj3ZFXgHm7hVW2?p=preview

Example interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // if this is cached, return the cached response.
  return Observable.of({body: 'Test'});

  return next
    .handle(customReq)
    .do((ev: HttpEvent<any>) => {
      if (ev instanceof HttpResponse) {
        // Cache this response
      }
    });
 }

Any help would be greatly appreciated.

My goal ultimately is to get this working with NG Universal's Transfer Module. If I fix this problem in the interceptor then I should have that all working and ready to go.

Edit: My assumption was wrong. The Angular HttpClient Interceptor Caching example works absolutely fine, it must be Angular Universal that is failing for me. (I updated Plunker with the working example from Angular, to prove that it's working for that case).

Here is my interceptor I use for Angular Universal.

constructor(private state: TransferState) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.method !== "GET") {
        return next.handle(request);
    }

    const STATE_KEY = makeStateKey(request.urlWithParams);
    const cachedResponse = this.state.get(STATE_KEY, null);

    if (cachedResponse) {
        return Observable.of(cachedResponse);
    }

    return next.handle(request).do(event => {
        if (event instanceof HttpResponse) {
            this.state.set(STATE_KEY, event.clone());
        }
    });
}

Maybe it's some sort of timing issue with the TransferState service, I am not sure.

I got it working. It makes sense but I can't believe it took me so long to realise the small fix. When I am returning the Observable of cachedResponse, I need to create a new HttpResponse object, since it's a class not just an interface. Thus like this:

return Observable.of(new HttpResponse<any>(cachedResponse));

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