Angular2: switchMap not canceling previous http calls

前端 未结 4 444
孤街浪徒
孤街浪徒 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条回答
  •  梦毁少年i
    2021-02-01 08:12

    The requests need to originate from the same underlying stream. Here's a factory function that will create an http service instance that should do what you want:

    function httpService(url) {
       // httpRequest$ stream that allows us to push new requests
       const httpRequest$ = new Rx.Subject();
    
       // httpResponse$ stream that allows clients of the httpService
       // to handle our responses (fetch here can be replaced with whatever
       // http library you're using).
       const httpResponse$ = httpRequest$
           .switchMap(() => fetch(url));
    
    
       // Expose a single method get() that pushes a new
       // request onto the httpRequest stream. Expose the
       // httpResponse$ stream to handle responses.
       return {
           get: () => httpRequest$.next(),
           httpResponse$
       };
    }
    

    And now the client code can use this service like this:

    const http = httpService('http://my.api.com/resource');
    
    // Subscribe to any responses
    http.httpResponse$.subscribe(resp => console.log(resp));
    
    // Call http.get() a bunch of times: should only get one log!!
    http.get();
    http.get();
    http.get();
    

提交回复
热议问题