Using Angular 2 http.post without a subscription? Or am I thinking about it wrong?

Is there a way to simply tell the server to update data without a subscription? Skipping the return statement and subscription seems to make an inert HTTP call.

In my case, my guy from the database created a bunch of stored procedures that do not return anything, and sometimes I want to do something simple, like this in my service:

public setItem(item: IRequestItem) { this.http.post('api/items', item); } 

and name it as follows:

 save() { var comp = this; this.items.forEach(function(item) { comp.service.setItem(item) }); } 

Instead, I should do something similar in the service:

 public setItem(item: IRequestItem) { return this.http.post('api/items', item); } 

And then name it like this:

 save() { var comp = this; this.items.forEach(function(item) { comp.service.setItem(item).subscribe(r => console.log(r)); }); } 

Which would return a lot of them:

 Response {_body: "", status: 204, ok: true, statusText: "No Content", headers: Headersโ€ฆ} _body : "" headers : Headers ok : true status : 204 statusText : "No Content" type : 2 url : "http://localhost:56018/api/items" __proto__ : Object 

I'm just studying, maybe I'm looking at it wrong. Can I interpret something in this Response object that will let me know if the operation failed or succeeded? Or is there another syntax that simply returns success or failure instead of the confusing "No content" response?

+7
angular observable angular2-services
source share
2 answers

To call a request, you need to call subscribe , but you do not need to return the request observed from the service and call it from this component, you can call the subscription service.

 setItem(item: RequestItem) { this.http.post('api/items', item) .subscribe({ error: e => console.error(e) }); } 

Now, in the above example, the service will immediately return before the request is completed, but the request and any errors registered in the service will be executed.

+3
source

Try the map method:

 public setItem(item: IRequestItem) { return this.http.post('api/items', item).map(data => data.json()); } 

Clarification: subscribe should be called in setItem or in save . Otherwise, the ajax request will fail.

-one
source

All Articles