首先检索数据以设置默认表单值? (角度2)

Retrieve data first in order to set default form values? (Angular2)

问题

我正在设置一个相当复杂的表单,每次我提交 PATCH 请求时,值都会重置为 null。

在表单控件中,当我尝试将默认值设置为服务中加载的数据时,它不起作用,因为数据直接不可用 away/has 未保存到 public model = Model[]

代码

   getControls() {
     let controlObj = {}

     for (var i = 0; i <= 7; i++) {
       this.field1 = "field-1-" + i

       testObj[this.field1] = new FormControl({value: this.model.name}, Validators.required)

     }
     this.controls = testObj
     return this.controls;
   }



   ngOnInit() {

     this.myService.getData()
       .subscribe(
         settings => {
           this.model = model;
           console.log(this.model)

         },
         error => console.error(error)
       )

     console.log(this.model)


     this.settingsForm = new FormGroup(
       this.getControls()
     )

   }

 }

总结

new FormControl({value: this.model.name} 无法检索此值,因为该服务不会保存要在组件内再次使用的数据。

在 运行 其他函数之前,我是否可以先在组件中保存从 get 请求中检索到的信息?

我有点困惑,为什么服务里面的 console.log(this.modal) 请求 returns 数据,而 returns 外面的那个请求 null。

如果您需要更多代码,请告诉我 - 我已尝试使用最少的代码以避免混淆。谢谢!

I'm a little confused as to why the console.log(this.modal) inside the service request returns the data, but the one outside returns null.

因为是异步过程。

console.log(this.model) outside subscribe 可能会在 this.model 收到任何值之前首先执行,这就是为什么它显示 null.

如果你想在 this.model 有值之后执行 getControls,那么将你的代码更改为

ngOnInit() {
    this.myService.getData()
       .subscribe(
         settings => {
            this.model = model;
            this.settingsForm = new FormGroup(
               this.getControls()
            )   
         },
         error => console.error(error)
       );
}