Reputation: 131
I want to fill update form fields to be filled with user existing data on page load. & I'm calling function for getting user data on my component.ts file like this
ngOnInit() {
const res = this.getUserDetails();
console.log(res);
this.updateForm = this.fb.group({
name: [this.userData.name, Validators.required],
email: [this.userData.email, [Validators.required, Validators.email]],
mobile: [this.userData.mobile, Validators.required],
image: [this.userData.image]
});
}
getUserDetails() {
this.amen.getUserDetails(this.params).subscribe(
(response) => {
this.handleResponse(response);
console.log('Response------------------------', response);
return response;
},
(error) => {
console.log('Error: ', error);
}
);
}
handleResponse(response) {
return this.userData = {
name: response.responseData.name,
email: response.responseData.email,
mobile: response.responseData.mobile,
image: response.responseData.user_img
};
}
But it gives me undefined on this line & also data doesn't show on reactive forms
console.log(res);
Upvotes: 0
Views: 346
Reputation: 22213
Use patchValue
Try like this:
this.amen.getUserDetails(this.params).subscribe(
(response) => {
this.updateForm.patchValue(this.handleResponse(response));
...
},
(error) => {
console.log('Error: ', error);
}
);
Explaination: In Reactive Forms, if we need to update the input elements on the form from our component class, we use setValue and patchValue
We use patchValue, when we want to change only a subset of the form element and not all the elements of the form. For all the elements, use setValue
Upvotes: 3
Reputation: 935
this is because you're assigning the value before they're actually fetched from the server. put
const res = this.getUserDetails();
console.log(res);
inside you're subscription method and you'll get what you want
Upvotes: 0