gpt4 book ai didi

javascript - 如何将服务中的数据分配给 JSON?

转载 作者:行者123 更新时间:2023-12-03 00:45:36 26 4
gpt4 key购买 nike

我正在制作 Angular 6 应用程序,其中我正在制作一个 Angular 动态表单,其中数据来自 JSON 动态形式。

JSON:

  jsonData: any = [
{
"elementType": "textbox",
"class": "col-12 col-md-4 col-sm-12",
"key": "project_name",
"label": "Project Name",
"type": "text",
"value": "",
"required": false,
"minlength": 3,
"maxlength": 20,
"order": 1
},
{
"elementType": "textbox",
"class": "col-12 col-md-4 col-sm-12",
"key": "project_desc",
"label": "Project Description",
"type": "text",
"value": "",
"required": true,
"order": 2
},
{
"elementType": "dropdown",
"key": 'project',
"label": 'Project Rating',
"options": [
{ "key": 'average', "value": 'Average' },
{ "key": 'good', "value": 'Good' },
{ "key": 'great', "value": 'Great' }
],
"order": 3
}
];

在下拉列表中,我想从服务调用中获取options数组..

到目前为止,您可以看到我已将其硬编码在选项中..

dynamic-form.component.ts中的服务:

  getDropdownValues(url,token) {
this.service.get(url,token).subscribe(res => {
console.log(res.data);
});
}

res.data 返回以下内容,

  {
data: [
{ "key": 'average', "value": 'Average' },
{ "key": 'good', "value": 'Good' },
{ "key": 'great', "value": 'Great' }
]
}

此数据数组将成为 JSON 中的选项..

到目前为止,我已经在 .ts 文件中给出了 JSON,但稍后它将是一个单独的 .json 文件。

工作堆栈 Blitz :https://stackblitz.com/edit/angular-x4a5b6-ng8m4z

请帮助我将来自服务 (res.data) 的数据放置到 JSON 内的下拉options 中。

最佳答案

您必须问问自己您收到了哪些数据以及您需要哪些数据。一般来说,您可以有,例如<​​/p>

getOptions():Observable<any[]>
{
//of, create an observable
return of(
[{key:"option1",data:["option1_1","option_1_2"]},
{key:"option2",data:["option2_1","option_2_2","option_2_3]},..
])
}

getModel():Observable<any[]>
{
return of(
[{key:"option1",...},
{key:"option2",..}
])
}

您必须使用 switchMap 来接收 fullModel。 switchmap 使您不会收到除内部电话之外的第一个电话。是一种不连接订阅的方法

getFullMode():Observable<any[]>
{
return getOptions().pipe(switchMap(
opts=>{
return getModel().pipe(map(mod=>{
//..here transform "mod" using the values of opts
//e.g.
let option=opts.find(p=>p.key=mod.key);
mod.options=option.data
}))
})
)
}

嗯,你的情况更容易,因为只有一个“选项”和一个唯一的“选项”,anf json 是固定的。

getFullJson(url,token) 
{
this.service.get(url,token).pipe(map(opt=>{
//we don't want return opt, else this.jsonData transformed.
let element=this.jsonData.find(e=>e.elementType=='dropdown');
if (element)
element.option=res.data
return this.jsonData
}))
}).subscribe(res=>console.log(res));

如果你的json来自可观察的,不使用map,请使用switchmap。 SwitchMap,等待外层调用结束进行第二次

getFullJson(url,token) {
this.service.get(url,token).pipe(switchMap(opt=>{
//we don't want return opt, else this.jsonData transformed.
//to transform data use pipe(map)
return this.service.getJsonData(pipe(map(jsonData=>{
let element=jsonData.find(e=>e.elementType=='dropdown');
if (element)
element.option=res.data
return this.jsonData
}))
}).subscribe(res=>console.log(res));

关于javascript - 如何将服务中的数据分配给 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com