Reputation: 699
I have a class with a model like this:
model = new questions(
1, // Id
'', // Name
'', // LastName
'undefined', // Gender
'undefined', // Filling Status
...
)
The I have a service that makes a GET
request to an API, and the response is like this:
{
"id": "5b6f",
"name": "John",
"lastName": "Doe",
"gender": "Male",
"fillingStatus": "Single",
...
}
How can I populate the model with this response, should I iterate to the object?
Thanks for your help!
Upvotes: 2
Views: 2291
Reputation: 56936
Angular have a very good tutorial on this exact theme.
https://angular.io/guide/dynamic-form
This uses reactive forms.
If you are not familiar with reactive forms you might want to do these tutorials first:
https://angular.io/guide/reactive-forms
https://angular.io/guide/form-validation
Basically, in the dynamic form tutorial, an HTTP request is made to the server to get form data using a service.
(the tutorial actually uses hardcoded data in a service but it is easy to swap this out for an HTTP request)
Once the data is retrieved it used to dynamically generate a reactive form.
The questions are then iterated to render the view and to render suitable form controls. The view hooks into the reactive form. You won't find a better tutorial.
Upvotes: 1
Reputation: 36580
Use the spread operator like this:
let json = {
"id": "5b6f",
"name": "John",
"lastName": "Doe",
"gender": "Male",
"fillingStatus": "Single",
}
const model = {...json}
console.log(model);
Keep in mind that this is new syntax and not all browsers might support this syntax. So it is smart to transpile this code to ES5 syntax using babel.
Upvotes: 0