Reputation: 201
The Problem
I'm setting up quite a complicated form, and each time I submit a PATCH request the values reset to null.
In the form control when I try to set the default value to data loaded in the service it will not work, as the data is not available straight away/has not been saved to public model = Model[]
The Code
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()
)
}
}
Summary
new FormControl({value: this.model.name}
cannot retrieve this value as the service does not save the data to be used again inside the component.
Is there a way for me to save the information retrieved from the get request inside the component first before running the rest of the functions?
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.
Let me know if you need more code - I've tried to get away with the bare minimum to avoid confusion. Thanks!
Upvotes: 0
Views: 256
Reputation: 1726
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.
Because it is asynchronous process.
console.log(this.model)
outside subscribe
probably will executed first before this.model
receive any value, that is why it display null.
If you want getControls
executed after this.model
has value, then change your code to
ngOnInit() {
this.myService.getData()
.subscribe(
settings => {
this.model = model;
this.settingsForm = new FormGroup(
this.getControls()
)
},
error => console.error(error)
);
}
Upvotes: 1