我試圖獲取https://angular.io/guide/dynamic-form中的動態窗體示例,該示例處理從我設置的Django API返回的元數據。angular.io指南中的動態窗體示例的異步版本
https://plnkr.co/edit/Nks8fD?p=preview
Django的API(從文檔生成的一個拷貝)是不是現在可在網上,所以我假裝在應用程序的API調用/ question.service.ts這樣的:
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.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;
});
}
}
但是,這並不工作 - 它提供了一個錯誤「無法讀取屬性未定義的‘有效’」 ,這表明this.questions沒有得到填充(因爲表單正在檢查有效的表單元素)。事實上,如果我添加一個ngOnInit和console.log(this.questions),我可以看到它是空的。我如何填充this.questions?我也嘗試運行this.service.getQuestions((questions)=> {this.questions = questions;});在ngOnInit中,具有相同的結果。如何解決承諾時更新約束問題?
我在stackoverflow上發現了一個類似的問題,這個問題沒有解決Setting Values From API for Angular 2 Dynamic Form當用戶點擊一個按鈕來解決這個問題時,開發者最終生成了表單問題。不幸的是,這不是我的選擇。