Valeriy
Valeriy

Reputation: 1435

How to send POST request via angular's HttpClient?

I want to send POST request via angular's HttpClient.

This is my typescript code:

saveEvent() {
        let header = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.post(this.eventUrl, JSON.stringify(this.data), { headers: header });
}

And my HTML code:

<button (click)="saveEvent()">Click me!</button>

I have no any forms, just want send JSON to server via POST-request. Request is not sent as I see at chrome console. How to fix this?

Upvotes: 0

Views: 3563

Answers (2)

user6277510
user6277510

Reputation:

Two things here.

  1. It is not a good practice to make http requests from event handlers. Makes your component less conducive to unit testing.

  2. There is no subscription.

Here is how the code ought to look like.

a. Your component which has the template.

<button (click)="saveEvent()">Click me!</button>

b. Your component class code, which will have a constructor and the dependency injected of a service provider

saveEvent(): void{

  this._serviceProvider.PostData(this.data)
  .subscribe(data => {
    console.log(JSON.stringify(data));
    //Show Some Message. Say pop a dialog/modal confirming the data save.
  })

}

c. The code in the service provider that posts the data and makes the actual HTTP call.

public PostData(data: any): Observable<any> {


            //Check if you need access tokens. Usually posts need access tokens. 
             let access_token: string = "";

            let url: string = "https://YourPostDataUrl/PostdataEndPoint";
            let headers = new Headers({
                'Authorization': 'Bearer ' + access_token,
                'Content-Type': 'application/json'
            });

            let options = new RequestOptions({ headers: headers });

            return this._http.post(url, data, options)
                .map(res => res.json())
                .catch(this.handleError)

}

Upvotes: 2

Yakov Fain
Yakov Fain

Reputation: 12378

You need to subscribe to any HTTP request, including post to make it work. Your code just declares your intention to perform the post request. Here's an example where I do HTTP POST of a form:

https://github.com/Farata/angulartypescript/blob/master/code-samples/chapter12/client/src/app/restclientpost/app.component.ts

Upvotes: 2

Related Questions