Angular2 FormBuilder和嵌套对象属性返回undefined

时间:2016-09-16 20:21:30

标签: angular typescript

我刚刚用TypeScript和Angular2弄湿了脚。我正在使用具有嵌套对象结构的API。我希望我的模型能够从API镜像资源。模型/资源,"查询",在TypeScript中定义:

'number' => 'required|numeric|digits_between:1,10'

我的表单组件是这样的:

// inquiry.ts
export class Inquiry {
  name: {
    first: string,
    last: string
  };
  email: string;
  phone: string;
  question: string;
}

我点击路线时遇到的错误是:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InquireService } from './inquire.service';
import { Inquiry } from './inquiry';

@Component({
  selector: 'inquire-form',
  templateUrl: './inquire-form.component.html'
})
export class InquireFormComponent implements OnInit {
  inquiryForm: FormGroup;
  inquiry = new Inquiry;

  constructor(
    private formBuilder: FormBuilder,
    private inquireService: InquireService) {}

  ngOnInit(): void {
    this.buildForm();
  }

  buildForm(): void {
    this.inquiryForm = this.formBuilder.group({
      'firstName': [
        this.inquiry.name.first, [
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(50)
        ]
      ], ...
  }
}

当我记录Error: Uncaught (in promise): TypeError: Cannot read property 'first' of undefined 时确实this.inquiry.name,但我不明白为什么。我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题是Inquiry对象上的所有属性都没有初始化,所以它们都是默认值undefined。由于重要的name未初始化,因此尝试访问其任何属性(firstlast)都将失败。

在构造函数中设置它:

constructor() {
    this.name = {} as any; // too lazy to give first/last properties
}

或在声明中初始化它:

class Inquiry {
    name = {} as {
        first: string,
        last: string
    };
    email: string;
    phone: string;
    question: string;
}

或者如果你想在声明中明确地保留类型而不依赖于类型推断:

class Inquiry {
    name: {
        first: string,
        last: string
    } = {} as any;
    email: string;
    phone: string;
    question: string;
}