在我的Angular 2应用程序中,我有几个不同的组件来显示不同组的数据。每个不同的组都有不同的API服务调用。但是,除了不同的数据集之外,每个数据集的表格显示/布局本身都是相同的。
在每个组的组件中,我像这样使用服务调用(这个调用用于"group1")。我在我的group1.component.ts中订阅我的OnInit中的数据:
ngOnInit() {
this.group1Service.getGroup()
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
}现在,我想要做的是通过抽象出表格显示来减少重复(即让它变干),这样我就可以把它作为一个子视图放到每个组件视图中。例如,组件1的视图如下所示("table-display“是在下面的代码中抽象出来的部分):
<div class="page-view">
<div class="page-view-left">
<comp1-left-panel></comp1-left-panel>
</div>
<div class="page-view-right">
<div class="page-content">
<table-display></table-display>
</div>
</div>
</div>我的问题是,如何将正确的服务调用(即正确的组件)绑定到每个组件的"table-display“?我应该在这里使用@Input,或者使用方括号绑定吗?
发布于 2017-02-04 03:51:27
是的,您将在表格显示组件上使用输入,并从父组件填充它:
<table-display [Data]="arrayOfData"></table-display>在表中定义数据的位置-显示为:
@input Data: Array<any>;发布于 2017-02-04 03:53:53
您可以将所需数据作为Input传递给table-display组件。
如果所有组件共享相同类型的结构以在表中显示数据。然后,我建议为公共数据创建一个单独的类,并传递该公共类的对象。
您可以在每个组件中编写一个映射器函数,该函数将向table-display返回所需的数据,或者,如果它是一个简单的类似JSON的结构,那么您可以动态地传递它。
e.g
假设有4个属性需要在表显示中显示,我们创建了common.ts
export class Common {
col1: string; #whatever data structure you need
col2: number;
col3: number[];
col4: Object;
constructure(col1: any,col2: any,col3: any,col4: any){
this.col1 = col1;
//set other attributes similarly
}
}在component1.component.ts中为否
import {Common} from './path_to_common.ts'
#other imports here
@component {
selector: 'app-component1',
template: "your about template"
}
export class Component1Component implements OnInit{
common: Common; #this is the common attribute you will pass to **table-display**
constructure(component1_service: Component1Service){
}
ngOnInit(){
#get your data from service here
#now set **common** attribute here by settings 4 attributes we defined
#e.g
this.common = new Common(service_record.col1,service_record.col2....)
}
}就是这样,现在您可以通过以下方式将此common属性作为输入传递:
在组件模板中
<table-display [common]="common"></table-display>现在编写TableDisplayComponent
import {Input} from '@angular/core'
`import {Common} from './path_to_common.ts'
#other imports here
@component {
selector: 'table-display'
template: `what ever your template is to show table`
}
export class TableDisplayComponent{
@Input() common: Common; #This common will be passed as input from all of your components
}https://stackoverflow.com/questions/42030487
复制相似问题