简体   繁体   English

将数据从Angular 8应用传递到Laravel后端以进行编辑

[英]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. 我正在使用前端的Angular 8和后端的Laravel构建的CRUD应用程序。 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. 前端是SPA,CRUD应用程序的“更新”功能正在捕获编辑表单上的更新数据,然后通过服务将其解析到后端。

The problem is after updating the data on the form I get null values when I dump on the backend controller in Laravel. 问题是更新表格上的数据后,当我在Laravel中的后端控制器上转储时,我得到空值。 Am using put method on the backend 我在后端使用put方法

Edit.component.html where I update the data which is populated dynamically on each input field via ngModel Edit.component.html,我在其中更新通过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 Edit.component.ts文件

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 Laravel后端路线

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

Laravel Controller Laravel控制器

  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 首先在模板中用ngForm注册变量,然后在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 然后在组件中访问值使用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 . 由于您将singleUser用作表单值的[(NgModel)] (双向绑定),因此数据将呈现到singleUser But you are trying the form which is not used any where in the form html. 但是您正在尝试在html表单中的任何地方都不使用的表单。

use this.form instead of singleUser you will be able update your table data. 使用this.form而不是singleUser您将能够更新表数据。

component.html 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.. :) 我希望这有帮助.. :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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