我只是用TypeScript和Angular2弄溼我的腳。我正在使用具有嵌套對象結構的API。我希望我的模型能夠從API中鏡像資源。該模型/資源,「查詢」,如打字稿定義:Angular2 FormBuilder和嵌套的對象屬性返回undefined
// 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
確實undefined
,但我不明白爲什麼。我究竟做錯了什麼?
你只是說明了'name'屬性的類型簽名是什麼,但實際上並沒有初始化zed它。 –
嗯。當我創建新的查詢實例(在構造函數之上)時,它沒有初始化嗎? – Brandon
據我所知,你只是宣稱一個Inquiry對象包含4個屬性,一個名字爲'{first:string,last:string}'和'email','phone'和'question'字符串類型。沒有一個屬性被明確地初始化,所以它們只有它們的默認值('undefined')。 –