Javascript 在Angular 4.3中的http.get返回的JSON上操作
在我的中,我试图通过JSON将动态表单控件提供给表单生成器,类似于angular.io上的动态表单教程。我无法操作从http.get()请求返回的JSON数据。我可以对整个对象进行console.log,但是如果我尝试记录一个子对象,我会在控制台中得到“undefined” 这是我的组件文件:Javascript 在Angular 4.3中的http.get返回的JSON上操作,javascript,json,angular,typescript,Javascript,Json,Angular,Typescript,在我的中,我试图通过JSON将动态表单控件提供给表单生成器,类似于angular.io上的动态表单教程。我无法操作从http.get()请求返回的JSON数据。我可以对整个对象进行console.log,但是如果我尝试记录一个子对象,我会在控制台中得到“undefined” 这是我的组件文件: export class TestComponent implements OnInit { dataSource: Observable<any>; questions: Question
export class TestComponent implements OnInit {
dataSource: Observable<any>;
questions: QuestionBase<any>[] = [];
results: QuestionBase<any>[] = [];
constructor(private http: HttpClient) {
this.dataSource = this.http.get('/questions');
}
ngOnInit() {
this.dataSource.subscribe(
data => {
this.results = data['contactInfo'];
console.log(this.results[0].controlType);
this.results.forEach((item: QuestionBase<any>) => {
if(item.controlType == 'text') {
console.log(item.controlType);
this.questions.push(new TextQuestion(item));
}
else if(item.controlType == 'dropdown') {
console.log(item.controlType);
this.questions.push(new DropdownQuestion(item));
}
});
console.log(this.questions);
},
err => {
console.log("Cannot get JSON data. Error Code: %s, URL: %s",
err.status, err.url)
},
() => console.log('Done')
);
}
}
编辑#2在将JSON文件更新为“controlType”而不是使用“type”的早期版本后,我未能重新启动节点服务器。我认为服务器将自动为新编辑和保存的文件提供服务,但似乎必须重新启动服务器才能做到这一点。问题结束您能否提供
/questions
示例回答?如果我使用console.log(this.results)代码>我得到如下结果:(11)[{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…}]0:{key:“firstName”,globalLabel:“First Name”,type:“text”,order:“text”,order:“text”,required:“1”}1:{key:“lastName”,globalLabel:“Last Name”,type:“text”,required:“true”,order:“2”。。。继续所有子对象。忽略我之前的回答。我没有注意到HttpClient
@EricJobe,我在您在上述评论中发布的结果中没有看到controlType。返回未定义的console.log的确切内容是什么?好吧,让我感到尴尬。我已经将JSON文件更新为“controlType”,而不是以前的“type”,但没有重新启动我的节点服务器,因为更新认为它会自动为更新后的文件提供服务器。重新启动服务器后,代码按预期工作。谢谢大家的帮助。有时只需要另一双眼睛就可以了。你能提供/questions
示例响应吗?如果我使用console.log(this.results)代码>我得到如下结果:(11)[{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…},{…}]0:{key:“firstName”,globalLabel:“First Name”,type:“text”,order:“text”,order:“text”,required:“1”}1:{key:“lastName”,globalLabel:“Last Name”,type:“text”,required:“true”,order:“2”。。。继续所有子对象。忽略我之前的回答。我没有注意到HttpClient
@EricJobe,我在您在上述评论中发布的结果中没有看到controlType。返回未定义的console.log的确切内容是什么?好吧,让我感到尴尬。我已经将JSON文件更新为“controlType”,而不是以前的“type”,但没有重新启动我的节点服务器,因为更新认为它会自动为更新后的文件提供服务器。重新启动服务器后,代码按预期工作。谢谢大家的帮助。有时候只需要一双眼睛就够了。
{
"contactInfo": [
{
"key": "firstName",
"globalLabel": "First Name",
"controlType": "text",
"required": "true",
"order": "1"
},
{
"key": "lastName",
"globalLabel": "Last Name",
"controlType": "text",
"required": "true",
"order": "2"
},
{
"key": "streetAddress",
"globalLabel": "Street Address",
"controlType": "text",
"required": "true",
"order": "3"
}, ...}]