首页 > 解决方案 > Angular 10中POST请求的空值

问题描述

我正在使用 angular 10 进行示例项目。在这个我正在处理一个包含两个输入字段的页面,即:名字姓氏,它包含一个保存按钮。在输入名字和姓氏后单击“保存”按钮,应使用POST 请求将值保存在 API 中。

问题是,虽然 API 被调用(POST),但值(名字和姓氏)被存储为null

下面是代码文件

组件名.component.html

<div class="tab-pane fade in active show" id="home">
  <h4 class="mt-4">Update Employees</h4>
  <div class="bgShadow mt-4">
    <div class="row" formGroup="addEmployeeForm">
        <div class="col-sm-12 col-md-5">
          <div class="form-group">
            <label>First name</label>
            <input class="form-control" placeholder="First name" type="text" #firstName [value]="fName" formControlName="formcontrol_firstname">
          </div>
        </div>
        <div class="col-sm-12 col-md-5">
          <div class="form-group">
            <label>Last Name</label>
            <input class="form-control" placeholder="Last Name" type="text" #lastName [value]="sName" formControlName="formcontrol_lastname">
          </div>
        </div>
        <div class="col-sm-12 col-md-2 mt-2">
          <label></label>
          <div class="actionBtn mb-4 text-center">

-------------------- SAVE BUTTON---------------------

            <button class="btn primary-btn comBtn" type="button"
                    (click)="saveEmployeeData(firstName.value,lastName.value)">Save     
            </button>
          </div>
        </div>
    </div>

    <div>
      <table [dataSource]="dataSource" class="mat-elevation-z8" mat-table matSort>

        <!-- Position Column -->
        <ng-container matColumnDef="employeeId">
          <th *matHeaderCellDef mat-header-cell mat-sort-header> ID</th>
          <td *matCellDef="let element" mat-cell><a
            style="color: #137d59;text-decoration: none;"
            (click)="showUpdateEmployeeData(element)">{{element.employeeId}}</a></td>
        </ng-container>

        <!-- Position Column -->
        <ng-container matColumnDef="employeeName">
          <th *matHeaderCellDef mat-header-cell mat-sort-header>Employee Name</th>
          <td *matCellDef="let element" mat-cell> {{element.employeeName}} </td>

        </ng-container>

        <ng-container matColumnDef="action">
          <th *matHeaderCellDef mat-header-cell> Action</th>
          <td *matCellDef="let element" mat-cell>
            <button (click)="openDialog(element)" color="warn" mat-button>
              <mat-icon>delete</mat-icon>
            </button>
          </td>
        </ng-container>

        <tr *matHeaderRowDef="displayedColumns" mat-header-row></tr>
        <tr *matRowDef="let row; columns: displayedColumns;" mat-row></tr>
      </table>
    </div>

  </div>
</div>

组件名.component.ts

import {Component, OnInit} from '@angular/core';
import {MaintenanceService} from '../../../../../Services/Maintenance/Maintenance.service';
import {ItemsRequestModel} from '../../../../../../Customer/Models/Items/ItemsRequestModel';
import {MatTableDataSource} from '@angular/material/table';
import {union} from 'lodash';
import {DeleteDialogComponent} from 'src/app/SharedModules/Components/DeleteDialog/DeleteDialog.component';
import {MatDialog} from '@angular/material/dialog';
import {environment} from '../../../../../../../../environments/environment';
import {AddEmployeeModel} from '../../../../../Models/UpdateEmployees/AddEmployeeModel';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {HttpClient} from '@angular/common/http';

@Component({
  // tslint:disable-next-line:component-selector
  selector: 'app-UpdateEmployees',
  templateUrl: './UpdateEmployees.component.html',
  styleUrls: ['./UpdateEmployees.component.scss']
})
export class UpdateEmployeesComponent implements OnInit {
  displayedColumns: string[] = ['employeeId', 'employeeName', 'action'];
  public requestModel = new ItemsRequestModel();
  public dataSource: any;
  public result: any;
  public fName = '';
  public sName = '';
  public Name: any;
  Url: string = environment.apiGateway;
  // public addEmployeeModel = new AddEmployeeModel();


  addEmployeeForm: FormGroup;


  // tslint:disable-next-line:max-line-length
  constructor(public maintenanceService: MaintenanceService, public dialog: MatDialog, public formBuilder: FormBuilder, public http: HttpClient) {
  }

  ngOnInit(): void {
    this.maintenanceService.getUpdateEmployeeList(this.requestModel).subscribe(res => {
      if (res.length > 0) {
        const finalArray = union(this.result, res);
        console.log(finalArray);
        this.dataSource = new MatTableDataSource(finalArray);
        this.result = finalArray;
      }
    }, error => {
      console.log(error);

    });

    this.addEmployeeForm = this.formBuilder.group({
      formcontrol_firstname: new FormControl(null),
      formcontrol_lastname: new FormControl(null),
      CreatedBy: ['Mohit Sharma']
    });

  }


  openDialog(input): void {
    console.log(input);

    const dialogRef = this.dialog.open(DeleteDialogComponent, {
      width: '350px',
      data: 'Do you confirm the delete of this Employee?'
    });
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        // alert('running');
      }
    });
  }

  showUpdateEmployeeData(element: any): void {
    console.log('Show Data......');
    this.fName = element.firstName;
    this.sName = element.surName;
    console.log('First Name : ' + this.fName);
    console.log('Surname : ' + this.sName);
  }

// ------------- SAVING DATA USING SERVICES INSIDE METHOD-------------------

  saveEmployeeData(firstname: string, lastname: string) {
    console.log('Save Employee Data clicked...');
    if (firstname === '' || lastname === '') {
      alert('Please Enter First Name and Last Name');
    } else {
      console.log('saved successfully...');
      // --------------- TEST CODE ---------------
      const requestParams: AddEmployeeModel = {
        FirstName: firstname,
        SurName: lastname,
        CreatedBy: 'Mohit Sharma'
      };
      console.log(requestParams);
      this.maintenanceService.addEmployeeDetails(requestParams).subscribe(res => {
        console.log(res);
      }, error => {
        console.log(error);
      });
    }
  }
}

服务.ts

// ------------------------- POST REQUEST TO SAVE DATA -------------------------
  addEmployeeDetails(addEmployeeModel: AddEmployeeModel): Observable<any> {
    return this.http.post(this.Url + '/Employee', addEmployeeModel);
  }

模型文件 AddEmployeeModel.model.ts

export class AddEmployeeModel {
  FirstName: string;
  SurName: string;
  CreatedBy: string;
}

截图

在点击保存按钮之前

点击保存按钮后

控制台正在显示数据

值在 API 中存储为 Null

请问有什么解决办法吗?

标签: angulartypescript

解决方案


我发现了导致在 API POST 调用中发送空值的问题。问题是我没有在返回语句之前在我的服务文件中传递以下代码行,即:

const params = new HttpParams()
  .set('FirstName', `${addEmployeeModel.FirstName}`)
  .set('SurName', `${addEmployeeModel.SurName}`)
  .set('CreatedBy', `${addEmployeeModel.CreatedBy}`);

现在它工作正常。


推荐阅读