我从服务收到以下响应,其中包括 json 架构格式的表单定义。
现在我想在 Angular 分量中迭代这个响应。
所以我已经在一个 Formdata 变量中获取了像这样的所有架构元素。
res['tabs'].forEach(element => {
this.tablist.push(element);
});
this.tablist.forEach(element => {
this.FormData[element] = res['com'][element]['schema'];
this.FormValueData[element] = res['com'][element]['data'];
this.FetchValueParam[element] = res['com'][element]['data'];
});
现在我想访问 View 中 Formdata 的值,我已经为其编写了以下代码。
<form>
<div *ngFor='let input1 of FormData[element]['properties']'>
<label [for]='input1.type'> input1.title</label>
<input type='input1.type' [name]='input1.title'
[placeholder]='something'>
<br>
</div>
<br><br>
<button type="submit"> Submit </button>
</form>
但是我无法将其作为数组访问,因为它是一个 json 对象。我已经尝试过 Array.of() 和 Array.from() 但它无法处理以下错误。如何遍历 json 并创建表单字段?
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays
更新:当我使用这样的虚拟 json 对象时。我得到了想要的结果。所以我得到的是,ngFor 期望的类型和我作为 json 对象提供的类型之间存在严重的不匹配。
this.inputfield=
[{type:'email',name:'email',value:'',placeholder:"your email here"},
{type:'email',name:'email',value:'',placeholder:'your email
here'},{type:'email',name:'email',value:'',placeholder:'your
email here'},
{type:'email',name:'email',value:'',placeholder:'your email
here'},{type:'email',name:'email',value:'',placeholder:'your
email here'},
{type:'email',name:'email',value:'',placeholder:'your email
here'},{type:'email',name:'email',value:'',placeholder:'your
email here'},
{type:'email',name:'email',value:'',placeholder:'your email
here'},{type:'email',name:'email',value:'',placeholder:'your
email
here'}{type:'email',name:'email',value:'',placeholder:'your
email here'}];
当我在 json 模式验证器中检查它们之间的差异时, 我在控制台中显示的前者是作为对象来的,但上面是数组。
因此,我要么发送数组而不是对象,要么在运行时根据上述 json 模式创建一个数组或类。最好做什么?
最佳答案
假设 this.tablist 是一个字符串数组,您可以将在 this.FormData[element] 中创建的对象更改为数组:
this.tablist.forEach(element => {
Object.keys(res['com'][element]['schema']['properties']).forEach(inputKey => {
this.FormData[element] = [];
this.FormData[element].push(res['com'][element]['schema']['properties'][inputKey]);
}
this.FormValueData[element] = res['com'][element]['data'];
this.FetchValueParam[element] = res['com'][element]['data'];
});
然后在模板中使用它,如下所示。
<div *ngFor='let input1 of FormData[element]'>
此外,您没有在这一行上使用属性绑定(bind)(也就是说,如果组件中没有名为某些内容的变量):
[placeholder]='something'>
.
应该是
[placeholder]='"something"'>
关于javascript - 如何在 Angular 2 中迭代这个 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746731/