I found another method that will prevent subscribe() callbacks from being called. Here's an example interceptor that will refrain from calling downstream subscribers if a certain http header is present in the HttpResponse.
Be warned though, that this method doesn't really "throw the response away". Instead, it indefinitely delays the response. If you have code that uses timers (eg, some code that will error if a neither a success nor error response is received within 60 seconds), it could be a problem, because that's exactly how this method works - it just never responds.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
switchMap((event: HttpEvent<any>) => {
// In this example, I only care about checking valid http responses.
// But, if you also want to inspect errors, you might consider checking for HttpResponseBase or HttpErrorResponse
if (event instanceof HttpResponse) {
// Check if this response has a certain http response header set.
// If so, we throw the response away.
if (event.headers.has('my-custom-header')) {
// We intentionally return an Observable that will never complete. This way,
// downstream subscribers will never receive anything, and any .toPromise()
// conversions that may be present will also never be invoked because toPromise() only
// gets invoked when the Observable completes.
// It doesn't actually throw the response away, but rather, it makes the subscribers wait forever, so they will never get a response.
// Be careful if you use timeouts.
return new Subject<HttpEvent<any>>();
}
}
// The default case - we pass the response back through unmodified.
return Observable.of(event);
})
);
}
// These console.logs will not be called
this.http.get('/foo').subscribe(
data => console.log("success", data),
err => console.log("fail.", err)
);
// Neither will these
this.http.get('/foo').toPromise(
data => console.log("success", data),
err => console.log("fail.", err)
);