我试图在https://angular.io/guide/dynamic-form中使用从我设置的Django API返回的元数据中获取动态表单示例。
https://plnkr.co/edit/Nks8fD?p=preview(从文档中生成的文件复制而来)
目前还没有在线提供Django API,所以我假装app / question.service.ts中的API调用如下:
getQuestions(): Promise<QuestionBase[]> {
return new Promise(resolve => {
// Simulate server latency with 2 second delay
setTimeout(() => resolve(this.getQuestionsOriginal()), 2000);
});
}
this.getQuestionsOriginal()只返回一系列问题,例如:
QuestionBase<any>[] = [
new DropdownQuestion({
key: 'brave',
label: 'Bravery Rating',
options: [
{key: 'solid', value: 'Solid'},
{key: 'great', value: 'Great'},
{key: 'good', value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 3
}),
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
然后在app / app.component.ts的构造函数中,我试图检索问题并将它们分配给一个局部变量this.questions,它绑定到模板中,如下所示:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Job Application for Heroes</h2>
<dynamic-form [questions]="questions"></dynamic-form>
</div>
`,
providers: [QuestionService]
})
export class AppComponent implements OnInit {
questions = Array();
constructor(private service: QuestionService) {
this.service.getQuestions((questions) => {
this.questions = questions;
});
}
}
但这不起作用 - 它会产生错误&#34;无法读取属性&#39;有效&#39; of undefined&#34;,这表明this.questions没有填充(因为表单正在检查有效的表单元素)。事实上,如果我添加一个ngOnInit和console.log(this.questions),我可以看到它是空的。我如何填充this.questions?
我也试过运行this.service.getQuestions((questions)=&gt; {this.questions = questions;});在ngOnInit中,具有相同的结果。如何解决承诺时如何更新绑定的问题?
我在stackoverflow上发现了一个类似的问题,但未解决Setting Values From API for Angular 2 Dynamic Form当用户点击按钮解决此问题时,开发人员最终会生成表单问题。不幸的是,这不适合我。
答案 0 :(得分:2)
数据通过后,您的questions
实际上不是undefined
。检查一下:How do I return the response from an Observable/http/async call in angular2?和接受的答案,以了解为什么console.log
在此处打印未定义:
service.getQuestions().then(questions => this.questions = questions);
console.log(this.questions);
但对你的实际问题。由于这是一个异步操作,因此响应需要一段时间才能通过。在此之前,角度试图显示模板。因此,我们可以设置一个条件,即在DynamicFormComponent
填充之前不显示questions
。所以在AppComponent
做:
<dynamic-form *ngIf="questions" [questions]="questions"></dynamic-form>
这将解决您的问题! :)