json - 使用 JSON 数据创建的 Angular 动态表单
问题描述
亲爱的读者。我正在尝试使用已为红色的 Json 数据制作动态表单。动态表单基于 Angular 的示例,如下所示:https ://angular.io/guide/dynamic-form
我所做的编辑是我从外部 Json 文件中读取数据并尝试加载这些数据,而不是在链接中看到的文件“question.service.ts”中的硬编码文件。
这是我的 Json 文件的样子:
{
"formInfo": {
"name": "test"
},
"fields": [
{
"controlType": "textbox",
"key": "firstName",
"label": "Voornaam",
"required": true,
"value": "Mark",
"order": 1
},
{
"controlType": "textbox",
"key": "surName",
"label": "Achternaam",
"required": true,
"order": 2
},
{
"controlType": "textbox",
"key": "emailAddress",
"label": "Email",
"required": false,
"order": 3
},
{
"controlType": "dropdown",
"key": "brave",
"label": "Beoordeling",
"required": "",
"order": 4,
"options": {
"solid": "Solid",
"great": "Great",
"good": "Good",
"unproven": "Unproven"
}
}
]
}
我检索数据并作为可观察返回的函数(in question.service.ts)如下所示:
getQuestions2() : Observable<QuestionBase<any>[]> {
let questions: QuestionBase<any>[] = [];
const exampleObservable = new Observable<QuestionBase<any>[]>((observer) =>
{
let url = "../assets/exampleData.json"
this.http.get(url).subscribe((data) => {
for (let x of data['fields']){
if (x.controlType == "textbox"){
let textboxItem = new TextboxQuestion({
key: x.key,
label: x.label,
value: x.value,
order: x.order
})
questions.push(textboxItem);
}
else if (x.controlType == "dropdown"){
let dropDownItem = new DropdownQuestion({
key: x.key,
label: x.label,
value: x.value,
options: x.options,
order: x.order
})
questions.push(dropDownItem);
}
}
})
observer.next(questions.sort((a, b) => a.order - b.order));
})
return exampleObservable;
}
将服务与前端连接起来的代码如下所示:
export class AppComponent implements OnInit {
questions: any[];
constructor(private service: QuestionService) {
this.getaSyncData();
//this.questions = this.service.getQuestions();
//console.log(this.questions);
}
getaSyncData(){
this.service.getQuestions2()
.subscribe((data) => this.questions = data);
console.log(this.questions);
}
解决方案
我终于为那些将来会遇到类似问题的人解决了这个问题
即使我正确地从 JSON 文件中读取数据并在控制台中打印,我也无法将表单加载到 html 中。我在加载数据的 div 中添加了一个 *ngIf。在 Angular.io 的示例中,它位于 App.component.html 上的模板中。是的,就是这么简单。
推荐阅读
- flutter - 使 CachedNetworkImage 缩放以适合 ListTile 的高度
- selenium-chromedriver - chromedriver在请求时导致状态码429
- android - 如何使用 Firebase 数据库中的 Datasnapshot 获取多个节点的多个值?
- python - 我的 selenium 代码有时无法找到按钮,而在其他时间为什么?
- react-native - 如何在 react-native 中检测屏幕是否有圆角
- ruby-on-rails - 在 Rails 中获取和设置 json 列的键的简洁方法
- javascript - 在页面刷新时从浏览器 url 中删除 #id
- google-sheets - 条件改变时如何改变整个范围的风格?
- javascript - 服务器端文件更改后 Passport.js req.user 对象未定义(节点,快递)
- reactjs - 在 Simulate('change') 状态未更新后