When you click on the button, the getDatafromServer method is triggered. Tell me if switchMap is implemented correctly in Angular for one route. when pressed again, the previous request is canceled (if the old one has not yet arrived) and a new one is sent:

getDatafromServer() { of(`url1`).pipe(switchMap(url => this.httpGeneralService.getDataFromJsonServer(url))). subscribe(i => console.log(i)); } 

It seems to be true, but in the browser in the Network it is not visible that previous requests are canceled.

UPD: this version seems to be working:

  private requestPasswordSubject$ = new Subject(); private requestPassword = this.requestPasswordSubject$.pipe( switchMap(() => this.httpGeneralService.getDataFromJsonServer(`url1`)) ) .subscribe(response => { console.log(response); } ); getDatafromServer() { this.requestPasswordSubject$.next(); } 
  • whence the assumption that the previous request should be canceled? - Grundy
  • switchMap makes complete the previous Observable - Lex
  • and what, in this case, you have the previous one ? - Grundy

1 answer 1

switchMap will work correctly in the event that events at the press of a button will go from the stream. In this case:

 of(`url1`).pipe(switchMap(url => this.httpGeneralService.getDataFromJsonServer(url))) 

of('url1') is a cold thread that generates an event 1 time and closes (why do you do this?) I would say this is a useless code.

If you want to click on the button to send a request and unsubscribe from the stream, if the answer is not received, but a new event has come, you need to use the fromEvent + switchMap :

 const button = document.querySelector('button'); fromEvent(button, 'click').pipe( switchMap(() => this.httpGeneralService.getDataFromJsonServer(`url1`)) ).subscribe((response) => { console.log(response); }); 

switchMap subscribes to the fromEvent stream, accepts a factory as a parameter (in the RxJS concept, this is called a projection), calls this factory and receives a new stream (which returns this.httpGeneralService.getDataFromJsonServer('url1') ), subscribes to this stream, waits for a response if fromEvent generates an event earlier than the stream getDataFromJsonServer - SwitchMapSubscriber unsubscribes from getDataFromJsonServer and processes the new incoming event from the stream fromEvent .

  _next(value) { let result; const index = this.index++; try { result = this.project(value, index); // вызвали проекцию и получили поток } catch (error) { this.destination.error(error); return; } this._innerSub(result, value, index); } _innerSub(result, value, index) { const innerSubscription = this.innerSubscription; if (innerSubscription) { innerSubscription.unsubscribe(); // отписываемся от предыдущей проекции } }