What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1291
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 06:12

    rxjs 5.3.0

    I haven't been happy with .map(myFunction).publishReplay(1).refCount()

    With multiple subscribers, .map() executes myFunction twice in some cases (I expect it to only execute once). One fix seems to be publishReplay(1).refCount().take(1)

    Another thing you can do, is just not use refCount() and make the Observable hot right away:

    let obs = this.http.get('my/data.json').publishReplay(1);
    obs.connect();
    return obs;
    

    This will start the HTTP request regardless of subscribers. I'm not sure if unsubscribing before the HTTP GET finishes will cancel it or not.

提交回复
热议问题