我正在尝试使用 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/