PGH
PGH

Reputation: 2204

To perform POST http request by an dialog component

I have component called list which will display some title names from an api like this:

enter image description here

As shown in image, I have fab-button called Add. On clicking this fab-button. I am calling an dialog window (component name is add-customer). like this:

enter image description here

Now from this dialog window i want to fill input fields(i,e title and description) of the form and i want post it server, Means i want send http POST request on clicking SAVE button.

I am able call api using GET method.But for POST method,I am unable to do.

DEMO

In add-customer.ts i passing the values from the form to an function called postCustomer

I can see in this in the console:

enter image description here

I just want to know that how can assign this postCustomer function to POST method in service.ts file.

I am trying like this:

   public postCustomer(): Promise<IContact[]> {
    const apiUrl: string = 'api.........';

    return this.http.post<IContact[]>(apiUrl).toPromise();
  }

Upvotes: 0

Views: 2210

Answers (1)

SeleM
SeleM

Reputation: 9638

For POST method:

For POST methods you have a body to send, change your service to :

  public postCustomer(data): Promise<IContact[]> {
    const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts';

    return this.http.post<IContact[]>(apiUrl, data).toPromise();
  }

Then in your AddCustomerComponent refactor your method onAddCustomer() to:

 public onAddCustomer(): void {
    this.markAsDirty(this.addCusForm);
    this.postCustomer=this.addCusForm.value;
    console.log(this.postCustomer);
    this.service.postCustomer(this.postCustomer).then(
      (response)=> {
          console.log('POST called', response);

      }
    )
  }

Do not forget to import your Service in the same component:

import {Service} from '../service';

And inject it in the constructor:

constructor(private fb: FormBuilder, private service: Service) { }

NOTE: I do not get why you're using Promises over Observables, you have to change them for more consistency and powerful operators.

Upvotes: 1

Related Questions