Sole
Sole

Reputation: 3340

Service in Angular 6 to do a post request with JSON data from a form

I have a form in Angular 6 and that data gets sent (Post request) to the server. What I want to do is write the following code into a service and then inject that back into the submit function, so far it is:

onSubmit() {
    this.http.post("/api/inc",
      this.serviceForm.value,
      {
        headers: new HttpHeaders().set("Content-Type", "application/json")
      }
    ).subscribe((response: any) => {
      console.log(response);//On success response
      this.router.navigate(['/inc/confirmation']);
    }, (errorResponse: any) => {
      console.log(errorResponse); //On unsuccessful response
    });
    if(this.serviceForm.invalid) {
      this.serviceForm.setErrors({ ...this.serviceForm.errors, 'required': true });
      return;
    }
  }

Upvotes: 1

Views: 670

Answers (1)

Zarna Borda
Zarna Borda

Reputation: 735

You can write post request code into a service file and then inject that request function into onSubmit() function to make a request call

inc.service.ts

postFormData(payload) {
   this.http.post("/api/inc", payload, { headers: new HttpHeaders().set("Content-Type", "application/json")});
}

In component.ts file:

constructor(private incService:IncService) {}

onSubmit() {
    if(this.serviceForm.invalid) {
       this.serviceForm.setErrors({ ...this.serviceForm.errors, 'required': true });
       return;
    }
    this.incService.postFormData(this.serviceForm.value).subscribe((response: any) => {
      console.log(response);//On success response
      this.router.navigate(['/inc/confirmation']);
    }, (errorResponse: any) => {
      console.log(errorResponse); //On unsuccessful response
    });
 }

Upvotes: 1

Related Questions