Angular2:将表单值转换为具有默认字段的Model的问题

时间:2017-01-10 10:19:55

标签: rest angular

我正忙于需要发布到REST API的Stock take表单。我有一个stockTake模型,它有三个字段,用默认值0初始化。三个字段" StockTakeID,IDKey和PackSize"不是需要输入数据的角度形式的一部分。我的问题是将具有默认值的这三个字段的模型提交给我的RestService。当我提交stockTakeForm.value时,我收到一个错误,因为这三个字段不属于提交的数据...我知道如何才能让它工作?

我的stock-take.model.ts:

export class StockTakeModel {

    constructor(
    StockTakeID: number = 0,
        IDKey: number = 0,
        BarCode: number,
        ProductCode: string,
        SheetNo: string,
        BinNo: string,
        Quantity: number,
        PackSize: number = 0) { }
}

my stock-take.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { RestService } from '../../services/rest.service';

import { StockTakeModel } from '../../models/stock-take.model';

@Component({
  selector: 'stock-take',
  templateUrl: './stock-take.component.html',
  styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
    stockTakeForm: FormGroup;   

  constructor(private fb: FormBuilder, private restService: RestService) { 
    this.stockTakeForm = fb.group({
        'sheetNo':['', Validators.required],
        'binNo':['', Validators.required],
        'barcode':['', Validators.required],
        'Qty':['', Validators.required]
    }); 
    }

  submitStockTake(stockTakeModel: StockTakeModel) {
      //console.log(stockTakeModel);

    this.restService.postStockTake(stockTakeModel)
    .subscribe(
    (res) => {
        console.log(res);
    },
    (res) => {
        console.log("failure: " + res);
    }
    );
    this.stockTakeForm.reset();
  }

  ngOnInit() {

  }
}

my stock-take.component.html:

<div class="row">
    <div class="col-md-6 col-md-push-3">
        <h1>Stock Take</h1>
        <br /><br />
        <form [formGroup]="stockTakeForm" role="form" (ngSubmit)="submitStockTake(stockTakeForm.value)">
            <input type="text" placeholder="Enter Sheet Number" class="form-control" id="sheetNo" [formControl]="stockTakeForm.controls['sheetNo']" name="sheetNo">
            <input type="text" placeholder="Enter Bin Number" class="form-control" id="binNo" [formControl]="stockTakeForm.controls['binNo']" name="binNo">
            <input type="number" placeholder="Enter Barcode" class="form-control" id="bCode" [formControl]="stockTakeForm.controls['barcode']" name="barcode">
            <input type="number" placeholder="Enter Quantity" clas="form-control" id="Qty" [formControl]="stockTakeForm.controls['Qty']" name="quantity">
            <button class="btn btn-block" [disabled]="!stockTakeForm.valid">Submit</button>
        </form>
    </div>
</div>

更新了stock-take.component:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { RestService } from '../../services/rest.service';

import { StockTakeModel } from '../../models/stock-take.model';

@Component({
  selector: 'stock-take',
  templateUrl: './stock-take.component.html',
  styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
    stockTakeForm: FormGroup;
    stockTakeModel: StockTakeModel;

  constructor(private fb: FormBuilder, private restService: RestService) { 
    this.stockTakeForm = fb.group({
        'sheetNo':['', Validators.required],
        'binNo':['', Validators.required],
        'barcode':['', Validators.required],
        'Qty':['', Validators.required]
    });
    }

    doStockTake(val: any) {
        //console.log("val:" + JSON.stringify(val));
        this.stockTakeModel = new StockTakeModel(0, 0, val[Object.keys(val)[2]], '', val[Object.keys(val)[0]], val[Object.keys(val)[1]], val[Object.keys(val)[3]], 0);

//  console.log(this.stockTakeModel);
    console.log(JSON.stringify(this.stockTakeModel));
    }

  submitStockTake(stockTakeModel: StockTakeModel) {
      //console.log(stockTakeModel);

    this.restService.postStockTake(stockTakeModel)
    .subscribe(
    (res) => {
        console.log(res);
    },
    (res) => {
        console.log("failure: " + res);
    }
    );
    this.stockTakeForm.reset();
  }

  ngOnInit() {

  }
}

2 个答案:

答案 0 :(得分:0)

我不了解模板中的构造[formControl]。 至少应该有[ngModel]。

Usualy我使用[(ngModel)]进行双向通信。不是[formControl]。

因此,您的模板代码应如下所示:

<div class="row">
    <div class="col-md-6 col-md-push-3">
        <h1>Stock Take</h1>
        <br /><br />
        <form [formGroup]="stockTakeForm" role="form" (ngSubmit)="submitStockTake(stockTakeForm.value)">
            <input type="text" placeholder="Enter Sheet Number" class="form-control" id="sheetNo" [(ngModel)]="stockTakeForm.controls['sheetNo']" name="sheetNo">
            <input type="text" placeholder="Enter Bin Number" class="form-control" id="binNo" [(ngModel)]="stockTakeForm.controls['binNo']" name="binNo">
            <input type="number" placeholder="Enter Barcode" class="form-control" id="bCode" [(ngModel)]="stockTakeForm.controls['barcode']" name="barcode">
            <input type="number" placeholder="Enter Quantity" clas="form-control" id="Qty" [(ngModel)]="stockTakeForm.controls['Qty']" name="quantity">
            <button class="btn btn-block" [disabled]="!stockTakeForm.valid">Submit</button>
        </form>
    </div>
</div>

答案 1 :(得分:0)

一种解决方法是创建一个新变量,例如: stockTakeModel: StockTakeModel;

如果这不起作用(正如你所说的那样抱怨未定义),你也可以将它实例化为一个空的Object,如下所示:

stockTakeModel = {};

编辑,所以你把你的代码更改为:我还添加了一些console.log来显示未定义的位置,因为有一点关于它的问题。

stockTakeModel: StockTakeModel; // undefined at this point (or empty if you have defined it as empty above)!

// use Object keys to access the keys in the val object, a bit messy, but will work!
submitStockTake(val: any) {
  this.stockTakeModel = 
    new StockTakeModel(0, 0, val[Object.keys(val)[2]], '', val[Object.keys(val)[0]], 
       val[Object.keys(val)[1]], val[Object.keys(val)[3]]);  

  // console.log(this.StockTakeModel); // now it should have all values!

  this.restService.postStockTake(this.stockTakeModel)
     .subscribe(d => { console.log(d)} ) // just shortened your code a bit 
  this.stockTakeForm.reset();
  }

编辑:除了上面的解决方案之外,最后问题终于解决了。这是因为您的StockTakeModel - 类未正确声明值未定义或实际为空。所以修改你的课程:

export class StockTakeModel {

    constructor(
    public StockTakeID: number = 0, // you were missin 'public' on everyone
        public IDKey: number = 0,
        public BarCode: number,
        public ProductCode: string,
        public SheetNo: string,
        public BinNo: string,
        public Quantity: number,
        public PackSize: number = 0) { }
}

另请注意,在“已更新”代码中,表单中仍有(ngSubmit)="submitStockTake(stockTakeForm.value),因此不会调用您创建的doStockTake - 方法。