所以我用switchMap()
取消了HTTP调用,只有最后一次通话保持到了服务器合并来自单独的组件rxjs电话......这里是服务:Angular2:如何通过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();
这工作得很好,一个组件......可是,问题是,如果我叫httpService(url)
从不同的组件我仍然会得到HTTP流的多个实例,并且肯定的是,它会每个组件只有一个SINGLE流(由于switchMap()
抵消重复http.get()
PER同一组件)......我的目标是让所有的部件被取消了,只发送到服务器的最后一个,占到所有来电。
我所缺少的是把所有的数据流从不同的组件合并在一起的httpService
内有switchMap()
只与最后一次最后的最后一个处理的能力... ...棘手:/
如果我理解你想要做你需要使用什么服务https://angular.io '而不是创建的/docs/ts/latest/tutorial/toh-pt4.html和共享'的HTTPRequest $的一个实例的'HttpService的()'中的每个组件。 – martin