mongodb - 定義されていないオブジェクトの値に対する Angular2 FormGroup の patchValue エラー
私が解決しようとしている問題は、HTTPリクエストとフォームグループに関連しています。編集ページのフォームに既存の値をパッチしようとしています。
エラーは、値がデータベース(mongoDB)に存在しない場合に発生します。その値は、追加されたオブジェクトにのみ存在します。以下のコードは、私のリクエスト、formgroup、およびpatchValueです。
this.takeawayService.getByName(this.id).subscribe(data => {
this.takeaway = data.takeaway[0];
console.log(this.takeaway);
this.formData = this.fb.group({
address : ['', Validators.required],
city : ['', Validators.required],
county : ['', Validators.required],
postCode : ['', [Validators.required,
Validators.pattern('[A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]? [0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}')]],
bio : ['', Validators.required],
image : '',
_id : '',
cuisines: [],
isPublic: [false, Validators.required],
'openingHours': fb.group({
'monday': fb.group({
opened: [false],
open: [''],
close: ['']
})
})
});
this.formData.patchValue({
address: this.takeaway.address,
city: this.takeaway.city,
county: this.takeaway.county,
postCode: this.takeaway.postCode,
bio: this.takeaway.bio,
image: this.takeaway.image,
_id: this.takeaway._id,
cuisines: this.takeaway.cuisines,
isPublic: this.takeaway.isPublic,
openingHours: {
monday:{
opened: this.takeaway.openingHours.monday.opened,
open: null,
close: null
}
}
});
リクエストによって返されていない値をパッチしようとしたときに受け取るエラーは、'TypeError: undefined is not an object (evaluating '_this.takeaway.openingHours.monday')' です。
この問題を三項演算子を使って解決しようと試みましたが、うまくいきませんでした(openingHours.monday.opened ? openingHours.monday.opened : false)。どんな助けでも本当にありがたいです。自分の問題に似たものを検索してみましたが、うまく見つかりませんでした。
編集: 一部のフィールドをオプションとして設定して、フォームグループでテンプレートを使用しようとしましたが、うまくいきませんでした。値はまだ未定義です。
export interface Takeaway {
address: String,
city: String,
county: String,
postCode: String,
bio: String,
image: String,
_id: String,
cuisines: [String],
isPublic: Boolean,
openingHours?: {
monday?: {
opened?: Boolean,
open?: Date,
close?: Date,
}
}