Angular http.post without .subscribe callback

后端 未结 5 2137
野的像风
野的像风 2020-12-05 23:56

I\'m wondering if I can make just a http post request without subscribing on callbacks, something like this

 this._http.post(\'/list/items/u         


        
5条回答
  •  离开以前
    2020-12-06 00:21

    I had the same question but then I figured out that I actually don't care if someone subscribes to the observable. I just want the POST request sent in any case. This is what I came up with:

    postItem(itemData) {
        var observable = this.http.post('/api/items', itemData)
            .map(response => response.json()) // in case you care about returned json       
            .publishReplay(); // would be .publish().replay() in RxJS < v5 I guess
        observable.connect();
        return observable;
    }
    

    The request is sent as soon as connect() is called. However, there is still an observable that the caller of postItem can subscribe to if required. Since publishReplay() is used instead of just publish(), subscribing is possible even after the POST request completed.

提交回复
热议问题