未定义对象值上的Angular2 FormGroup patchValue错误

时间:2017-10-23 12:52:15

标签: mongodb angular typescript undefined formgroups

我一直试图解决的问题与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不是对象(评估'_this.takeaway.openingHours.monday')'。

我试图用三元来解决这个问题而没有运气(openingHours.monday.opened?openingHours.monday.opened:false)。任何帮助都会很棒。我试图找到与我的问题类似的任何东西,但没有运气。

编辑: 我试图通过将一些字段设置为可选但没有运气来使用我的formgroup模板。该值仍未定义。

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,

       }
   }

0 个答案:

没有答案