【问题标题】:Access nested JSON elements in Angular2 Service访问 Angular2 服务中的嵌套 JSON 元素
【发布时间】: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

标签: json angular


【解决方案1】:

根据您发布的 JSON 对象,您需要这样做:

    data.forEach((questionGroup: QuestionGroup) => {
       questionGroup.forEach((item: any) => { 
       //you can replace 'any' with the appropriate class that represents 'item'
          //access item properties, like controlType
          console.log(item.controlType);
       });
    });

【讨论】:

  • 现在项目的console.log根本没有被调用,但是console.log数据被执行了2次
【解决方案2】:

看起来项目的值是一个对象数组。也许我弄错了,但我认为item[0].controlType 应该返回您正在查找的结果。

【讨论】:

    【解决方案3】:

    您的问题是,当您仔细查看 JSON 时,您要访问的数据位于数组 ventureReason 中。你想要那个数组的内容,所以稍微改变一下你的映射,应该没问题!

    .map(res => res.json().ventureReason) // extract the data from the array
    

    所以你的item.controlType 是未定义的,因为没有属性,因为你的singleitem 实际上只包含属性ventureReason 和整个数组。

    这里是

    Demo

    【讨论】:

    • 这些答案的效果如何,有没有解决您的问题? :)
    猜你喜欢
    • 2016-10-29
    • 2016-07-16
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 2021-07-09
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多