This is the method that I created:
getUser(endpoint: string, email: string) {
const url = this.envConfigurationService.baseEndpoint '/' conf.apiPrefix '/' endpoint email;
this.loadingService.loadingOn();
return this.http.get(url).pipe(
finalize(() => this.loadingService.loadingOff()),
catchError((err) => {
this.manageError(err);
return throwError(err);
}),
tap(() => this.toastrService.success('OK')),
);
}
and here's how I call it in the component.ts:
searchUser() {
this.backendIntegrationService.getUser('user?code=', encodeURIComponent(this.form.value.email)).subscribe({
next: (res) => {
if (res['result'] === 'OK') {
this.userresponse = res['body'];
this.usermessage = res['message']
}
else {
this.errorResponse = res;
}
},
error: err => {
this.errorResponse = err;
}
});
console.log(this.userresponse)
this.entityConfiguration.inputFields.forEach(field => {
console.log(this.userresponse)
let value = null;
value = this.userresponse[field.name];
if (field.disabled) {
this.formControls[field.name] = this.fb.control({value: value, disabled: true});
} else {
this.formControls[field.name] = this.fb.control(value);
}
});
this.form = this.fb.group(this.formControls);
}
For some reason, the object this.userresponse only get populated at the second call (second time I push the search user button), even though I get the values from the backend at the first time.
What am I doing wrong?
CodePudding user response:
It's an async operation. You call your service and then proceed with your function. Inside your subscribe block the variable will be set but at a later time. In the meantime the code has reached your console.log()
statement and prints out an undefined value (as it is undefined at that point).
You'll want to wait for the call to complete (ie. your next
block) before processing the response.
You mention that the variable is defined the second time around. Which it is-- but it's the response from the first call.