【发布时间】:2018-04-02 14:01:51
【问题描述】:
我想在更新产品之前编辑产品并显示详细信息。我已经开发了一个表单以及相关的组件和服务,但是,我在我的 Angular 4 应用程序中收到了一条错误消息ERROR TypeError: Cannot read property 'product_name' of undefined。我在“update-product.component.html:
<div class="container">
<form [formGroup]="productUpdateForm" (ngSubmit)="updateproduct()" class="form-signin" novalidate
[class.was-validated]="productUpdateForm.invalid && (productUpdateForm.dirty || productUpdateForm.touched)">
<h2 class="form-signin-heading text-center">Update Product</h2>
<div class="alert alert-danger" *ngIf="dataInvalid">
<p *ngFor="let error of formErrors">{{ error }}</p>
</div>
<div class="form-group">
<label class="sr-only">Product Name</label>
<input type="text" formControlName="product_name" class="form-control" [class.is-invalid]="dataInvalid"
placeholder="Enter Name" required [(ngModel)] = "data.product_name">
<div class="invalid-feedback">
Name is required.
</div>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="productUpdateForm.invalid" *ngIf="!formSubmitting">Update</button>
<button class="btn btn-lg btn-primary btn-block" type="button" [disabled]="formSubmitting" *ngIf="formSubmitting">Updating...</button>
</form>
</div>
而我的update-product.component.ts如下:
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router, RouterModule, ActivatedRoute} from '@angular/router';
import {HttpErrorResponse} from '@angular/common/http';
import { HttpClient , HttpHeaders } from '@angular/common/http';
import { UpdateProductService } from './update-product.service';
@Component({
selector: 'app-update-product',
templateUrl: './update-product.component.html',
styleUrls: ['./update-product.component.scss']
})
export class UpdateProductComponent implements OnInit {
productUpdateForm: FormGroup;
dataInvalid = false;
formErrors = [];
formSubmitting = false;
id:number;
constructor(private UpdateProductService: UpdateProductService, private route: ActivatedRoute, private fb: FormBuilder) {
this.createForm();
}
createForm(){
this.productUpdateForm = this.fb.group({
product_name: ['', Validators.required],
description: ['', [Validators.required, Validators.maxLength(300)]]
});
}
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params['id'];
});
this.UpdateProductService.getProduct(this.id)
.subscribe(data => {
console.log(data);
this.data = data;
}
}
}
请注意,数据在输入框中正确显示,但是在控制台中,我收到了上述错误。
【问题讨论】: