Simplify submit Form Angular 7

1

I have this function and I do not know if it can be simplified because I think it's too long.

submitForm(){
  if(this.operatoId){ 
    this._oper.update(this.operatoId, this.registerForm.value).subscribe(
      (val) => {
          console.log("POST call successful value returned in body", val);
      },
      response => {
          console.log("POST call in error", response);
      },
      () => {
          console.log("The POST observable is now completed.");
      });
  } else{
    this._oper.create(this.registerForm.value).subscribe(
      (val) => {
          console.log("POST call successful value returned in body", val);
      },
      response => {
          console.log("POST call in error", response);
      },
      () => {
          console.log("The POST observable is now completed.");
      });
  }
  this._location.back();
  this.toastr.success('Grup', '',{disableTimeOut:true,closeButton:true, positionClass:'toast-bottom-right'});
}

Gracias!
    
asked by David 04.12.2018 в 10:32
source

1 answer

1

Two details:

  • It can be simplified, since the functions to handle the answers are the same:
  • submitForm(){
      const responseOK = 
        (val) =>  console.log("POST call successful value returned in body", val);
      const responseKO = response => console.log("POST call in error", response);
      const finish = () => console.log("The POST observable is now completed.");
    
      if(this.operatoId){ 
        this._oper.update(this.operatoId, this.registerForm.value).subscribe(
          responseOK, responseKO,finish);
      } else{
        this._oper.create(this.registerForm.value).subscribe(
          responseOK, responseKO,finish);
      }
      this._location.back();
      this.toastr.success('Grup', '',{disableTimeOut:true,closeButton:true, positionClass:'toast-bottom-right'});
    }
    
  • But study well what you are doing: the HTTP POST method should be used to create and the HTTP PUT method to modify if you want to have a standard REST interface
  • answered by 04.12.2018 / 11:30
    source