【发布时间】:2017-04-22 04:53:47
【问题描述】:
我已经按照本教程中的说明创建了一个具有动态表单的应用程序:https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
现在我想从服务器上的 json 文件加载问题,而不是硬编码问题。
JSON 看起来像这样:
{
"ventureReason":[
{
"label": "Venture Reason",
"controlType": "dropdown",
"options": [
{
"key": "solid",
"value": "Solid"
},
{
"key": "great",
"value": "Great"
}
]
}
],
"blablabla": [
{
"label": "Blablabla",
"controlType": "textbox",
"options": [
]
}
]
}
在QuestionService 中,我想根据controlType 的值构建问题。但是item.controlType 总是返回未定义。 data 包含整个 json 文件。
export class QuestionService {
questionUrl:string = `db`;
data:any;
questions : QuestionBase<any>[] = [];
constructor(
private http: HttpService
){}
getQuestions() {
return this.http.get(this.questionUrl)
.map(res => [res.json()])
.map(data => {
this.data = data;
return this.buildQuestions(data);
})
}
buildQuestions(data) {
console.log("data: "+ JSON.stringify(data)); //whole json file
let questions = [];
data.forEach((item: QuestionGroup) => {
console.log("item: " + JSON.stringify(item)); //whole json file
console.log("item: " + JSON.stringify(item.controlType)); //undefined
if (item.controlType == 'dropdown') {
item.controlType = 'dropdown';
questions.push(new DropdownQuestion(item));
}
else if (item.controlType == 'textbox') {
item.controlType = 'textbox';
questions.push(new TextboxQuestion(item));
}
});
return questions;
}
}
如何访问controlType 来构建问题?
【问题讨论】:
-
整个 JSON 对象
item: QuestionGroup应该代表哪一部分?我问是因为console.log("data: "+ JSON.stringify(data));和console.log("item: " + JSON.stringify(item));都会打印整个json文件(就像你在cmets中提到的那样)。 -
一项应为
ventureReason,另一项应为blablabla