Angular 6中的服务使用来自表单的JSON数据进行发布请求

时间:2019-03-10 00:25:34

标签: angular

我在Angular 6中有一个表单,该数据被发送(发布请求)到服务器。我想做的是将以下代码写入服务,然后将其重新注入到Submit函数中,到目前为止是:

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;
    }
  }

1 个答案:

答案 0 :(得分:1)

您可以将后请求代码写入服务文件,然后将该请求函数注入onSubmit()函数以进行请求调用

inc.service.ts

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

在component.ts文件中:

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
    });
 }