Angular 2/4:将服务层中promise函数的数组值分配给组件中的变量



我正在使用Promise调用服务层中的post函数,它会返回一个JSONArray。我可以在组件层中获取它,但无法分配给变量。

我尝试的是:

config;

ngOnInit() {
this.dataService.getTemplateData(this.templateId).then(result => this.config = result)
.catch(error => console.log(error));
}
:: result is printing jsonArray properly

我在控制台中收到以下错误

AppComponent.html:34 ERROR TypeError: Cannot read property 'forEach' of undefined
at DynamicFormComponent.webpackJsonp.../../../../../src/app/dynamic-form/containers/dynamic-form/dynamic-form.component.ts.DynamicFormComponent.createGroup (dynamic-form.component.ts:24)
at DynamicFormComponent.webpackJsonp.../../../../../src/app/dynamic-form/containers/dynamic-form/dynamic-form.component.ts.DynamicFormComponent.ngOnInit (dynamic-form.component.ts:19)
at checkAndUpdateDirectiveInline (core.es5.js:10843)
at checkAndUpdateNodeInline (core.es5.js:12341)
at checkAndUpdateNode (core.es5.js:12284)
at debugCheckAndUpdateNode (core.es5.js:13141)
at debugCheckDirectivesFn (core.es5.js:13082)
at Object.eval [as updateDirectives] (AppComponent.html:34)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
at checkAndUpdateView (core.es5.js:12251)

我期待的是:

config = [
{
"type": "input",
"label": "Full name",
"name": "name",
"placeholder": "Enter your name"
},
{
"type": "select",
"label": "Favourite food",
"name": "food",
"options": ["Pizza", "Hot Dogs", "Knakworstje", "Coffee"],
"placeholder": "Select an option"
},
{
"label": "Submit",
"name": "submit",
"type": "button"
},
];

以下是我的.html逻辑:-

<div class="app">
<dynamic-form [config]="config">
</dynamic-form>
</div>

我的服务层

getTemplateData(data:any):Promise{

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http
.post(this.templateDataUrl, data, options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}

正确初始化配置变量,我能够将数据分配给参数

config: any[] = [];

请分享dynamic-form.component的完整代码。跟踪问题会很容易。

DynamicFormComponent.createGroup (dynamic-form.component.ts:24)

在上面的行中,config是未定义的,这就是它抛出错误的原因u应该调用类似于的creatGroup()方法

this.dataService.getTemplateData(this.templateId).then(result => {
this.config = result;
this.creatGroup()
}).catch(error => console.log(error));

最新更新