HTTP Interceptor never finishes executing (finalization is never triggered)

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

Answer №1

The main concern lies with the presence of the Connection: Keep-Alive header, which maintains an ongoing connection.

The Connection general header dictates whether the network connection remains open after completing the current transaction. When set to keep-alive, the connection persists and does not close, enabling follow-up requests to be made to the same server.

This can lead to an Observable that never completes until the connection is ended.

Hence, this is not a flaw or error on your end. It seems likely that you have included this header in your HttpInterceptor, explaining why the issue arises only when the interceptor is added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function' To address this issue, I inserted '{initialN ...

Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module. module-to-test.ts import { config } from './app-config'; export const isSomethingWhatINeedSelector = createSelector( firstDependencySelector, secondDependencySelector ...

Tips for utilizing playFromPositionAsync method with expo-av Video in React Native

While working with the Video Expo component, I came across a prop called playFromPositionAsync. In the Video.d.ts file, it is defined like this: export default class Video extends React.Component<VideoProps, VideoState> implements Playback { ... ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

Is it possible to utilize BehaviourSubject across different modules in Angular?

I am looking to utilize the BehaviourSubject for sharing data between two components that belong to different modules. How can I achieve this goal? CurrenciesModule export class CurrenciesComponent implements OnInit { defaultCurrency: CurrencyModel; ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

How to access the types of parameters in a function type

I am working on a function that takes a value and default value as arguments. If the value is a boolean, I want the return type to match the type of the default value. Here is the function I have: export type DetermineStyledValue<T> = ( value: str ...

Leveraging TypeScript unions within functions to handle and throw errors

As a newcomer to TypeScript, I've encountered an odd error that I need help with. I have various objects sending data to the server and receiving fresh data back of the same object type. These objects use a shared method for sending the data, so I ap ...

What is the best way to show mat-select choices above a dialog box?

In my quest to find a solution, I came across this approach in the global css file: .cdk-global-overlay-wrapper, .cdk-overlay-container { z-index: 10000; } However, this method seems to cause issues with other dialog windows (such as the MatDatepicker ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Error message: Invalid input for directive, only numeric values are accepted

I need help with a directive that restricts non-numeric symbols in an input field. Below is the code for the directive: import { NgControl } from "@angular/forms"; import { HostListener, Directive } from "@angular/core"; @Direct ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

The Angular2-Recaptcha feature fails to load when navigating back in the browser

As I delve into the world of Angular Application development, I encounter an issue with Recaptcha. Everything works smoothly during application initialization. However, upon navigating to the next page and then attempting to go back using the browser' ...

Utilize the ngClass directive in conjunction with ngFor loop functionality

Currently, I am working on rendering a list of elements using the *ngFor directive in Angular. However, I have encountered an issue where only certain parts of the text within the list items should be bold based on specified requirements. I attempted to ac ...

Using Partial function input in TypeScript

I am in need of a function that can accept partial input. The function includes a variable called style, which should only have values of outline or fill, like so: export type TrafficSignalStyle = 'outline' | 'fill' let style: TrafficSi ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

What is the best method to utilize angular 2 cli for copying css and essential files to the dist folder?

After setting up my Angular 2 TypeScript solution and including the material Angular 2 npm package, I followed these steps: npm install -g angular-cli ng new PROJECT_NAME cd PROJECT_NAME ng build The files were successfully transferred from my source fol ...

Utilizing [src] syntax in Angular 2 and webpack to efficiently import images

When attempting to import an image in my Angular 2 application, I encountered an issue. I tried using the following code: <img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" /> However, the problem arose when using the [src] tag ...