我有问题,将异步数据传递给子组件.我试着编写动态表单生成器.当我尝试通过Observable调用json并将其传递给子组件时,问题就开始了.
服务:
generateSearchFields2(): Observable{ return this.http .get(this.API + 'searchFields') .map((res:Response) => { res.json().data as any; for (var i = 0; i < res.json().data.length; i++) { var searchField = res.json().data[i]; switch (searchField.component) { case "TextboxQuestion": let TXQ: TextboxQuestion = new TextboxQuestion({ key: searchField.key, label: searchField.label, value: searchField.value, required: searchField.required, order: searchField.order }); this.searchFieldModels.push(TXQ); console.log("TXQ: ", TXQ, this.searchFieldModels); break; case "DropdownQuestion": let DDQ: DropdownQuestion = new DropdownQuestion({ key: searchField.key, label: searchField.label, required: searchField.required, options: searchField.options, order: searchField.order }); this.searchFieldModels.push(DDQ); console.log("TXQ: ", DDQ, this.searchFieldModels); break; default: alert("DEFAULT"); break; } } return this.searchFieldModels.sort((a, b) => a.order - b.order); }) .catch(this.handleError); }
组件父:
generateSearchFields2() { this.service.generateSearchFields2() .subscribe(res => this.searchFields = res) }
Iam通过父模板中的INPUT指令将变量传递给child: [searchFields]="searchFields"
问题在子组件中,其中searchField
具有未定义的值.在这个孩子中,我将值传递给另一个服务,以创建formContros,但我也未定义.数据缺失从这里开始,在孩子:
@Input() searchFields: SearchBase[] = []; ngOnInit() { this.form = this.qcs.toFormGroup(this.searchFields); console.log("ONINIT DYNAMIC FORM COMPONENT: ", this.searchFields); }
请提示我如何能够传递异步变量,同时不会丢失数据
你可以做@Input() searchFields
一个二传手
private _searchFields: SearchBase[] = []; @Input() set searchFields(value SearchBase []) { if(value != null) { this.form = this.qcs.toFormGroup(this.searchFields); console.log("ONINIT DYNAMIC FORM COMPONENT: ", this.searchFields); } } get searchFields() : SearchBase [] { return this.searchFields; }
您还可以使用每次更新输入时调用的ngOnChanges(),但设置器通常更方便,除非执行的代码依赖于所设置的多个输入.