繁体   English   中英

Angular2将JSON对象传递给组件的构造函数

[英]Angular2 passing a JSON object to the constructor of a component

我有以下情形,其中第一个组件config.editor.component了大量处理并创建了各种不同的JSON对象。

我对这种方法感到满意。 此组件的模板,然后呈现另一个组成部分- api.entry.component使用* ngFor循环。 如何将在config.editor.component.ts中创建的JSON对象传递给api.entry.component的构造api.entry.component

我当前的模板如下所示:

<!-- loop and display all api components here -->
<ct-api-entry *ngFor="let api in apis"></ct-api-entry>

我想要传递给构造函数的对象实际上是上面看到的“ api”。 根据此代码在config.editor.component.ts文件中创建此对象,该代码执行所有操作,并为apis变量分配一个JSON数组:

 clicked(event){
      ipc.send('open-file-dialog');
      ipc.on('selected-directory', (event, obj) => {
        this.server_description = obj.description;
        this.features = obj.features;
        this.apis = obj.apis;
        this.wola_configs = obj.configs;
        this.connection_factories = obj.connection_factories;
      });
  }

我真正想要的是能够从我的api.entry.component.ts构造函数中的模板循环访问特定的api

import { Component } from '@angular/core';

@Component({
  selector: 'ct-api-entry',
  templateUrl: 'api.entry.component.html',
  styleUrls: ['api.entry.component.css']
})
export class APIEntryComponent {
//I NEED TO PASS THIS CONSTRUCTOR AN SPECIFIC JSON OBJECT FROM APIS IN THE CONFIG-EDITOR MAIN COMPONENT
  constructor() {
 //I WANT TO ACCESS MY JSON API OBJ IN HERE!
  }

}

我觉得这一定很简单,但我正在努力查看其工作原理! 请帮助我了解如何将* ngFor循环中的JSON对象传递到模板正在构建的组件的构造函数中。

使用ct-api-entry组件中的Input装饰器定义api

import { Component, Input } from '@angular/core';

@Component({
  selector: 'ct-api-entry',
  templateUrl: 'api.entry.component.html',
  styleUrls: ['api.entry.component.css']
})
export class APIEntryComponent {
   @Input() api: any;   
   constructor() {}
}

然后将其传递到模板中:

<ct-api-entry *ngFor="let api of apis" [api]="api"></ct-api-entry>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM