Angular 4无法读取undefined的属性'product_name'

时间:2018-04-02 14:01:52

标签: angular angular4-forms

我想在更新产品之前编辑产品并显示详细信息。我已经开发了一个表单以及相关的组件和服务,但是我在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;
      } 
  }
}

请注意,数据在输入框中正确显示,但是在控制台,我收到了上述错误。

2 个答案:

答案 0 :(得分:3)

您尚未在组件中声明data

    this.UpdateProductService.getProduct(this.id)
      .subscribe(data => {
        console.log(data);
        this.data = data;  // there is no variable data in your component
      } 
  }

您需要在使用之前声明它。

export class UpdateProductComponent implements OnInit {

  data:any="";

由于您未在html中声明并使用product_name data属性,因此会抛出此错误。

答案 1 :(得分:1)

您需要在插值中安全检查变量。

data?.product_name

在你的例子中

      <input type="text" formControlName="product_name" class="form-control" [class.is-invalid]="dataInvalid"
             placeholder="Enter Name" required [(ngModel)] = "data?.product_name">

上述ngModel数据已更改为data?。这将检查它的存在。