typescript - Angular 2 : switchMap not canceling previous http calls

标签 typescript angular rxjs

我正在尝试使用 switchMap 取消 Angular2 中任何以前的 http 调用。 代码基本上是

var run = ():Observable<any> => {
        var url = 'http://...'
        return this._http.get(url)
            .map(result => {
                return var xmlData:string = result.text()

            });
    }


    function pollTasks() {
        return Observable.of(1)
            .switchMap(() => run())
            .map(res => res)
    }

    // caller can do subscription and store it as a handle:
    let tasksSubscription =
        pollTasks()
            .subscribe(data => {
                console.log('aa'+data)
            });

所以我连续多次调用整个源并收到几个回复(即:aa+data)

我的印象是 switchMap 应该取消之前的调用。

最佳答案

请求需要来自相同的底层流。这是一个工厂函数,它将创建一个应该执行您想要的操作的 http 服务实例:

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$
   };
}

现在客户端代码可以像这样使用这个服务:

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();

关于typescript - Angular 2 : switchMap not canceling previous http calls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35765322/

相关文章:

node.js - undefined 不可迭代(无法读取属性 Symbol(Symbol.iterator))

angular - VS 代码- Angular : Experimental support for decorators Warning

javascript - 使用 jspm 配置运行 typescript angular2 应用程序的页面加载错误

javascript - 是否可以将一个简单的 Subject 变成一个 BehaviorSubject?

node.js - 具有联合类型的 ajv 数组

javascript - 动态表 Javascript - Angular 2

c# - 如何转换 propName : string: any in typescript in c# model?

javascript - Angular 4 styleUrls 文件未找到

javascript - NGRX Action /效果上的多个有效负载

javascript - 从 rxjs 订阅返回一个函数