所以我使用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$
};
}
来取消HTTP调用,只保留最后一次调用服务器...这是服务:
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();
以及使用此服务的组件:
httpService(url)
这适用于一个组件...但问题是,如果我从不同的组件调用switchMap()
,我仍然会得到多个HTTP流的实例,当然,它只是一个单一的流组件(由于http.get()
取消重复的httpService
PER SAME组件)...我的目标是取消所有组件的所有呼叫,并且仅考虑发送给服务器的最后一个呼叫。
我缺少的是能够将所有流从switchMap()
内的不同组件合并在一起,并且label.adjustsFontSizeToFitWidth = true
只处理最后一个最后一个... ...棘手......: /
答案 0 :(得分:1)
不要直接从请求返回observable,而是从数据创建observable。像这样:
function httpService(url) {
const httpRequest$ = new Rx.Subject();
let httpResponse$ = new Rx.Subject();
httpRequest$.switchMap(() => fetch(url)).subscribe(data => httpResponse$.next(data))
return {
get: () => httpRequest$.next(),
httpResponse$
};
}
答案 1 :(得分:0)
构造函数(私有_http:Http,私有appStore:AppStore){
this.httpRequest$ = new Subject();
this.httpRequest$
.map(v=> {
return v;
})
.switchMap((v:any):any => {
console.log(v);
if (v.id==-1||v.id=='-1')
return 'bye, cancel all pending network calls';
return this._http.get('example.com)
.map(result => {
var xmlData:string = result.text()
});
}).share()
.subscribe(e => {
})
...
并推送数据:
this.httpRequest$.next({id: busId});
这很好用,我现在可以有一个服务,我可以管理所有网络电话,也可以取消之前的电话......
见下图,随着新来电的进入,之前的电话被取消。 请注意我如何设置慢速网络,延迟时间为4秒,以便提供所有正常工作...