2

我一直试图解决的问题与 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 (evalating '_this.takeaway.openingHours.monday')”。

我曾尝试使用三元来解决这个问题,但没有成功( opensHours.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,

       }
   }
4

0 回答 0