Angular http.post without .subscribe callback

2019-02-08 11:58发布

I'm wondering if I can make just a http post request without subscribing on 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();

3条回答
做个烂人
2楼-- · 2019-02-08 12:39

I do not think you can.

http.post (and get, put, delete, etc) returns a cold Observable, i.e. an Observable for which "its underlying producer is created and activated during subscription" (https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339#.tofgfsou4).

This means the the function represented by the Observable is activated only with the subscribe method.

查看更多
对你真心纯属浪费
3楼-- · 2019-02-08 12:40

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-02-08 12:49

I'm using conversion to Promise (requires rxjs):

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();
  }
}
查看更多
登录 后发表回答