1
votes

I used observable subscribe inside foreach, and inside the subscribe i set a value in the formGroup, but outside foreach i don't get the value from the formGroup

ependFromApis.forEach(element => {
 if (this.formGroup.get(element.defaultValue.pathVariable).value) {
    this.http.dependFromAPI(this.formGroup.get(element.defaultValue.pathVariable).value).subscribe(item => {
        this.formGroup.get(element.field).setValue(element.defaultValue.format(item[element.field]));
        this.formGroup.get(element.field).updateValueAndValidity();
    })
 }
})

console.log(this.formGroup.value);

i tried to use asynchronous api, but i get an error

Cannot read property 'formGroup' of undefined

ependFromApis.forEach(async function(element) => {
 if (this.formGroup.get(element.defaultValue.pathVariable).value) { // Cannot read property 'formGroup' of undefined
    let item = await this.http.dependFromAPI(this.formGroup.get(element.defaultValue.pathVariable).value).toPromise();
     this.formGroup.get(element.field).setValue(element.defaultValue.format(item[element.field]));
     this.formGroup.get(element.field).updateValueAndValidity();
 }
})
1
It's about a time to choose the answer (: - IAfanasov

1 Answers

0
votes

first code block - you don't change the formGroup value. you only subscribe to the external API. so the formGroup value would be changed only after dependFromAPI will emit value.

second code block - I clearly see a syntax error here.

ependFromApis.forEach(async (element) => { ... }
ependFromApis.forEach(async function(element) { ... }

the second option will lead to error Cannot read property 'formGroup' of undefined because this would point to a function instead of parent scope which you clearly expect. I hope this picture will help you to get the difference or at least make you smile (:

enter image description here