In my angular 8 project, I created a basic HttpInterceptor
that simply duplicates the original request and includes an additional parameter:
@Injectable()
export class RequestHeadersInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request.clone({
params: request.params.set('language', 'en')
}));
}
}
Within my service, I have a method called getFoos()
which sends an HTTP request intercepted by the RequestHeadersInterceptor
:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { Foo } from '.';
@Injectable({
providedIn: 'root'
})
export class FooService {
constructor(private http: HttpClient) { }
getFoos() {
return this.http.get<Foo[]>('/foos')
.pipe(
finalize(() => console.log('observable completed!'))
);
}
}
Lastly, in my component, I subscribe to getFoos()
:
fooService.getFoos().subscribe(console.log);
Expected Output
[{ foo: 1 }, { foo: 2 }]
observable completed!
Actual Output
[{ foo: 1 }, { foo: 2 }]
The issue is that the finalize
function is not triggering. Why might this be happening?
Notes
- If the interceptor is removed, the
finalize
function works as expected. - To provide the interceptor to the module, I used the following approach:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestHeadersInterceptor } from './shared/http-requests';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: RequestHeadersInterceptor, multi: true },
]
);
I updated the interceptor code to clone and modify the request instead of passing it as-is.
I tried a demo inspired by @PierreDuc's demo but couldn't reproduce the issue in the demo. This discrepancy could involve request or response headers.
Response Headers on live system API
Cache-Control: no-store, no-cache, must-revalidate, max-age=0 Cache-Control: post-check=0, pre-check=0
Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Connection: keep-alive
Content-Language: en-US
Content-Length: 42
Content-Type: application/json;charset=utf-8
Date: Tue, 21 Jan 2020 15:44:33 GMT
Pragma: no-cache
Pragma: no-cache
Server: nginx/1.16.1
X-Content-Type-Options: nosniff
X-Powered-By: Servlet/3.1
Request Headers on live system API
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Authorization: Basic xyzABC123
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Cookie: check=true; anotherCookie=1; bla=2;
Host: some.page.com:11001
Pragma: no-cache
Referer: https://some.page.com
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36