简体   繁体   中英

Passing data from Angular 8 app to Laravel backend for editing purpose

Am working on a CRUD application built using Angular 8 on the frontend and Laravel on the backend. The frontend is a SPA, on the Update functionality of the CRUD application am capturing the updated data on the edit form , parsing it to the backend via a service.

The problem is after updating the data on the form I get null values when I dump on the backend controller in Laravel. Am using put method on the backend

Edit.component.html where I update the data which is populated dynamically on each input field via ngModel

<form #editForm=ngForm (ngSubmit)="onSubmit()">

<div class="card-header childheader">Update Details</div>
    <div class="card-body">
         <div class="form-group row">
         <div class="col-sm-12">
            <label for="childFirstName">Child Name</label>
            <input 
                type="text" 
                name="childName" 
                class="form-control" 
                [ngModel]="singleUser?.name"
                id="childName" 
                placeholder="Child FirstName">
        </div>
    </div>
    <div class="form-group row">
         <div class="col-sm-6">
             <label for="childAge">Child Age</label>
            <select 
                class="form-control" 
                id="chAge" 
                name="childAge"
                [ngModel]="singleUser?.age" 
                required>
                <option value="" selected disabled> Child's Age</option>
                <option value="1"> 1 </option>
                <option value="2"> 2 </option>
                <option value="3"> 3 </option>
            </select>
        </div>
        <div class="col-sm-6">
            <label for="childGender">Child Gender</label>
            <select 
                class="form-control" 
                id="childGender" 
                name="childGender" 
                [ngModel]="singleUser?.gender" 
                required>
            <option value="" style="display:none"> Child's Gender</option>
                <option value="Male"> Male</option>
                <option value="Female"> Female </option>
            </select>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-12">
            <button 
                type="submit" 
                class="btn btn-lg btn-success btn-block" 
                [disabled]="!editForm.valid">Update Details </button>
        </div>
    </div>
    </div>
</form>

Edit.component.ts file

import { Component, OnInit } from '@angular/core';
import { SharedService } from 'src/app/Services/shared.service';
import { AuthService } from 'src/app/Services/auth.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  public singleUser : any[];
  public error = null;

  public form = {
    childName: null,
    childAge: null,
    childGender: null
  };

  constructor(
    private Shared : SharedService,
    private Auth:AuthService,
  ) { }

  //Pass the data to the backend via a common service
  onSubmit(){
    this.Auth.editedData(this.form).subscribe(
      data => console.log(data),
      error => console.log(error)
    );
  }

  ngOnInit() {
     //Pass the data to be edited to the view
     this.Shared.edit$.subscribe(message => this.singleUser = message);
  }

}

Auth Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  private baseUrl = 'http://localhost/Laravel-anngular-spa/backend/public/api';

  constructor(private http:HttpClient) {}

  //Pass data to the backend
  editedData(data:any){
    return this.http.post(`${this.baseUrl}/editedData` , data);
  }
}

Laravel Backend route

   Route::put('editedData', 'SubmitFormController@updateData');

Laravel Controller

  public function updateData(Request $request){
        dd($request->all());
    }

If you want to get form data you need to do like this.

First register variable with ngForm in template then pass in the data in ngsubmit

<form (ngSubmit)="onSubmit(registerForm)" #registerForm="ngForm">
    <div class="form-group">
      <label for="UserName">Your email</label>
      <input
        type="text"
        ngModel
        class="form-control"
        id="UserName"
        name="UserName"
        required
      />
      <div
        *ngIf="
          registerForm.controls.UserName?.errors?.required &&
          registerForm.controls.UserName?.touched
        "
        class="alert alert-danger"
      >
        Email is required
      </div>
    </div>

    <div class="form-group">
      <label for="password">Your password</label>
      <input
        type="password"
        ngModel
        class="form-control"
        id="Password"
        name="Password"
        required
      />
      <div
        *ngIf="
          registerForm.controls.Password?.errors?.required &&
          registerForm.controls.Password?.touched
        "
        class="alert alert-danger"
      >
        Password is required
      </div>
    </div>

    <button
      type="submit"
      class="btn btn-success"
      [disabled]="!registerForm.form.valid"
    >
      Submit
    </button>
  </form>

Then in the component to access value use formValue.value.something

Full code

onSubmit(formValue: NgForm) {
    const registerModel: AccountModel = {
      UserName: formValue.value.UserName,
      Password: formValue.value.Password
    };

    return this.authService
      .register(registerModel)
      .subscribe(
        res => this.toastr.success("Create account success"),
        error => this.toastr.error("Something went wrong")
      );
  }

since you are using singleUser as [(NgModel)] (Two way binding) to the form values, data will render into the singleUser . But you are trying the form which is not used any where in the form html.

use this.form instead of singleUser you will be able update your table data.

component.html

<form #editForm=ngForm (ngSubmit)="onSubmit()">

<div class="card-header childheader">Update Details</div>
    <div class="card-body">
         <div class="form-group row">
         <div class="col-sm-12">
            <label for="childFirstName">Child Name</label>
            <input 
                type="text" 
                name="childName" 
                class="form-control" 
                [ngModel]="form?.name"
                id="childName" 
                placeholder="Child FirstName">
        </div>
    </div>
    <div class="form-group row">
         <div class="col-sm-6">
             <label for="childAge">Child Age</label>
            <select 
                class="form-control" 
                id="chAge" 
                name="childAge"
                [ngModel]="form?.age" 
                required>
                <option value="" selected disabled> Child's Age</option>
                <option value="1"> 1 </option>
                <option value="2"> 2 </option>
                <option value="3"> 3 </option>
            </select>
        </div>
        <div class="col-sm-6">
            <label for="childGender">Child Gender</label>
            <select 
                class="form-control" 
                id="childGender" 
                name="childGender" 
                [ngModel]="form?.gender" 
                required>
            <option value="" style="display:none"> Child's Gender</option>
                <option value="Male"> Male</option>
                <option value="Female"> Female </option>
            </select>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-12">
            <button 
                type="submit" 
                class="btn btn-lg btn-success btn-block" 
                [disabled]="!editForm.valid">Update Details </button>
        </div>
    </div>
    </div>
</form>

I hope this helps.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM