I am trying to get started with creating a dynamic form in Angular 2, and I am using the setup from the Angular cookbook here as my starting point. I didn't have any issues with their setup, which just hard codes the data in the service as apposed to an api call. My issue is that when I try to use an api call the values don't seem to get set correctly.
In the Angular cookbook they have the question.service.ts file hard coded as:
getQuestions() {
let questions: QuestionBase<any>[] = [
new DropdownQuestion({
key: 'brave',
label: 'Bravery Rating',
options: [
{key: 'solid', value: 'Solid'},
{key: 'great', value: 'Great'},
{key: 'good', value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 3
}),
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
return questions.sort((a, b) => a.order - b.order);
}
}
And then from the app.component.ts file its simply called from the constructor as:
constructor(service: QuestionService) {
this.questions = service.getQuestions();
}
Which "questions" then binds to this in the app.component.ts template
<dynamic-form [questions]="questions"></dynamic-form>
I made changes to the question.service.ts to make an api call (now currently from a json file cause I don't have access to the api at home)
getFirstQuestion() {
return this._http.get(this.__questionJSONApiBaseUrl)
.map(data => data.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
Which is called from the app.component.ts as
ngOnInit() {
this.service.getFirstQuestion()
.subscribe(data => {
this.data = data;
if (data.Type == 'TextBox') {
let questions: QuestionBase<any>[] = [
new TextboxQuestion({
key: data.Title,
label: data.Text,
value: '',
required: true,
order: data.Id
})];
}
}
);
}
As you see I set the properties inside of the .subscribe(), but it doesn't seem to be working correctly because when it binds to [questions] in the template I get a "Cannot read property 'forEach' of undefined" error which comes from the question-control.service file which transforms the question to a FormGroup.
I know that the data is coming in because I can set an alert inside the if statement and see the data from the api call successfully. I believe my issue is that [questions] is binding before the data is ready. Can someone tell me a better way to do this or please provide any suggestions to what I'm doing wrong please? Is there a way I could set the properties in the api first?