1

I have been struggling to figure out why the HTTP requests are not been canceled using the switchMap operator.

import {Observable, of, Subject, Subscription, timer} from 'rxjs';
import {HttpClient} from '@angular/common/http';

constructor(private http: HttpClient) {}

ngOnInit(): void {
  const makeRequest$ = new Subject();
  const myResponse$ = makeRequest$.pipe(switchMap((id) => {
    const url = `${environment.apiUrl()}/accounts?${id}`;
    return this.http.get<any>(url, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
}));

myResponse$.subscribe(d => console.log(d));


makeRequest$.next(1);
makeRequest$.next(-3);
makeRequest$.next(3); }

The following code will print only the response of the third call, but won't cancel the rest of the HTTP requests.

I have an interceptor for HTTP failure responses, which will fire an alert due to the second call with the wrong id.

When I am trying this code in stackblitz it WORKS and requests are been canceled. I am using Angular10.

Any setting that I am missing?

7
  • 1
    It would be helpful if you provided the mentioned stackblitz to check how it differs from the code in the question
    – user13258211
    Commented Nov 30, 2020 at 9:38
  • And can you give some information about the enviroment where it is not working (I assume on your local machine)? Commented Nov 30, 2020 at 9:41
  • stackblitz.com/edit/… This is the working example. I have run it on my local machine and on AWS lambda. What king of additional info can be helpful? Thanks for the help! Commented Nov 30, 2020 at 10:06
  • 1
    a request takes at least a few milliseconds. I think that call to next is very quick, you need to simulate a delay
    – bubbles
    Commented Nov 30, 2020 at 10:17
  • On my env I call different API which takes a long time to respond. But the switchMap works in a sense that only the last response is passed to the subscriber but the in-flight request are not been canceled, As the do in the stackblitz example, with the same code on my machine Commented Nov 30, 2020 at 10:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.