javascript - Angular 2/4 : Assign array value from promise function in service layer to a variable in component

标签 javascript angular

我正在使用 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[] = [];

关于javascript - Angular 2/4 : Assign array value from promise function in service layer to a variable in component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54001487/

相关文章:

javascript - 不显示 Angular 指令的包装器

angular - 再次关于 Angular2 中的全局数据

angular - 如何在 Angular 4 和 @angular/cli 中动态添加组件到 NgModule?

javascript - Angular 将多个文件更改为内联模板

javascript - 如何根据 ng-options 设置隐藏值?

java - 如何让JSP调用Servlet更安全?

Angular 2 路由器链接激活,两个链接激活

maven - 如何配置 npm 以使用 maven 文件夹结构和 war 部署

javascript - 适用于 Skype Web 的 Chrome 扩展程序按键

javascript - 在不同的 js 文件中定义的单击事件处理程序和就绪处理程序 - 不工作