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?

Alex Portnoy
  • 426
  • 1
  • 5
  • 14
  • 1
    It would be helpful if you provided the mentioned stackblitz to check how it differs from the code in the question –  Nov 30 '20 at 09:38
  • And can you give some information about the enviroment where it is not working (I assume on your local machine)? – Sascha Hick Nov 30 '20 at 09:41
  • https://stackblitz.com/edit/angular-table-resize-dwk6tz?file=src%2Fapp%2Fresizable-table.component.ts 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! – Alex Portnoy Nov 30 '20 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 Nov 30 '20 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 – Alex Portnoy Nov 30 '20 at 10:37
  • @AlexPortnoy have a look to the network tab (chrome), you will notice that sometimes some requests are finished before `switchMap` cancels them (of course it depends on your internet speed) ... in your stackblitz exemple – bubbles Nov 30 '20 at 15:37
  • The speed of the response is not the case. I dont use the api as in the stackblitz example, i set a delay on my server for few sec ,so it takes few seconds to get a response while i make the calls one after another like in the example. – Alex Portnoy Dec 01 '20 at 06:52

0 Answers0