How can I post mat-form to API in angular

120 Views Asked by At

I have form, and I want post form values to API, but the values can not be posted, how can resolve this error?

  • my html form:
<form #adduser ="ngForm" (ngSubmit)="onAddUser(adduser.value)">
  <mat-form-field class="form-fild-width">
     <mat-label>First Name</mat-label>
     <input matInput name="first_name" ngModel required>
  </mat-form-field>
  <mat-form-field class="form-fild-width">
     <mat-label>Last Name</mat-label>
     <input matInput name="last_name" ngModel required>
  </mat-form-field>
  <mat-form-field class="form-fild-width">
     <mat-label>User Name</mat-label>
     <input matInput name="user_name" ngModel required>
  </mat-form-field>
  <mat-form-field class="form-fild-width">
     <mat-label>Password</mat-label>
     <input matInput name="password" ngModel required>
  </mat-form-field>
  <mat-action-row>
    <button mat-raised-button color="primary">Add User</button>
  </mat-action-row>
</form>
  • my typescript code:
onAddUser(data:{first_name: string, last_name: string, user_name: string, password: string}){
    console.log(data)
    this.http.post('https://my.users.com/users/add?', data,{headers:headers})
    .subscribe((result) => {
      console.warn(result);
    })
  }
1

There are 1 best solutions below

4
Yong Shun On

As mentioned that you pass the form value as the query string param, your current implementation in Angular is incorrect as you post the form value in the request body.

You should build the URL with the query string param.

onAddUser(data:{first_name: string, last_name: string, user_name: string, password: string}) {
  console.log(data)

  let queryStringPrams = "";
  let i = 0;

  for (let prop in data) {
    if (i > 0)
      queryStringParams  += `&${prop}=${encodeURIComponent(data[prop].toString())}`;
    else 
      queryStringParams  += `${prop}=${encodeURIComponent(data[prop].toString())}`;

    i++;
  }
    
  this.http.post('https://my.users.com/users/add?' + queryStringParams, null, { headers:headers })
    .subscribe((result) => {
      console.warn(result);
    });
}

Another approach is applying the HttpParams to pass the form value as the query string.

onAddUser(data:{first_name: string, last_name: string, user_name: string, password: string}) {
  console.log(data)

  let params: HttpParams = new HttpParams();

  for (let prop in data) {
    params = params.append(prop, data[prop]);
  }
    
  this.http.post('https://my.users.com/users/add', null, { headers:headers, params: params })
    .subscribe((result) => {
      console.warn(result);
    });
}