Angular2: switchMap not canceling previous http calls

前端 未结 4 439
孤街浪徒
孤街浪徒 2021-02-01 07:40

I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically

var run = ():Observable => {
        var url = \'         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 08:09

    I think when you use the switchMap operator, you can only cancel requests in the current data flow. I mean the events that occur on the same observable chain...

    If you call your pollTasks method several times, you won't be able to the cancel previous requests because they won't be in the same data flow... You create an observable chain each time you call the method.

    I don't know how you trigger the execution of your requests.

    If you want to execute your request each 500ms, you could try this:

    pollTasks() {
      return Observable.interval(500)
                    .switchMap(() => run())
                    .map(res => res.json());
    }
    

    In this case, if there are in-progress request after 500ms, they will be canceled to execute the new one

    With the approach, you just need to call once the pollTasks method.

    You can also trigger the asynchronous processing chain based on user events. For example, when characters are filled in inputs:

    var control = new Control();
    // The control is attached to an input using the ngFormControl directive
    control.valueChanges.switchMap(() => run())
                    .map(res => res.json())
                    .subscribe(...);
    

    There is a proposal to link / initiate more easily processing chain on DOM events (fromEvent)

    See this link:

    • https://github.com/angular/angular/issues/4062

提交回复
热议问题