2016-03-03 78 views
1

所以我用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()只与最后一次最后的最后一个处理的能力... ...棘手:/

+0

如果我理解你想要做你需要使用什么服务https://angular.io '而不是创建的/docs/ts/latest/tutorial/toh-pt4.html和共享'的HTTPRequest $的一个实例的'HttpService的()'中的每个组件。 – martin

回答

1

别t直接从请求中返回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$ 
    }; 
} 
+0

不幸的是,我想起来更加XHR请求与此设置:( – born2net

+0

你有例如plunker? – Sasxa

+0

我没有,但我会设置一个... TX – born2net

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秒的延迟提供一切工作正常...

enter image description here