Angular http.post without .subscribe callback

I am wondering if I can make an http mail request without subscribing to callbacks , something like this

this._http.post('/list/items/update?itemId=' + itemId + "&done=" + done, null); 

instead of this

  this._http.post('/list/items/update?itemId=' + itemId + "&done=" + done, null) .subscribe(); 
+19
angular typescript angular2-services
source share
4 answers

I do not think you can.

http.post (and get, put, delete, etc.) returns a cold observable, i.e. observable, for which:

its main producer is created and activated during the subscription

A source

This means that the function presented in Observable is activated only using the subscribe() method.

+13
source

I had the same question, but then I realized that I really do not care if someone subscribed to the observed one. I just want the POST request to be sent anyway. Here 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() called. However, it is still observed that the postItem caller can subscribe if required. Since publishReplay() used instead of publish() , subscription is possible even after the POST request is completed.

+8
source

I am using conversion in Promise (rxjs required):

 import 'rxjs/add/operator/toPromise'; @Injectable() export class SomeService { .... post(sp: Seatplace, date?: Date) : Promise<any> { return this.http.post( '/list/items/update?itemId=' + itemId + "&done=" + done, null ).toPromise(); } } 
+7
source

Like @picci points, regular observables are cold observables. If you want to make a request, try @ lex82's idea, here is a draft of rxjs 6:

 import { ConnectableObservable } from "rxjs" import { publish } from "rxjs/operators"; const myConnectableObservable: ConnectableObservable<any> = this._http.post('/list/items/update?itemId=' + itemId + "&done=" + done, null).pipe(publish()) as ConnectableObservable<any>; myConnectableObservable.connect(); 

which basically looks like a subscription, but without a real subscription.

https://blog.danlew.net/2018/09/25/connectable-observables-so-hot-right-now/

0
source

All Articles