在我的Angular 2应用程序中绑定正确的服务电话
问题描述:
在我的Angular 2应用程序中,我有几个不同的组件显示不同组的数据。每个不同的组都有不同的API服务调用。不过,除了不同的数据集,表格显示/布局本身对每一个都是相同的。在我的Angular 2应用程序中绑定正确的服务电话
在每个组的组件中,我使用的是这样的服务调用(这个是“group1”)。我订阅的数据在我的OnInit在我group1.component.ts:
ngOnInit() {
this.group1Service.getGroup()
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
}
现在,我想要做的是什么(即让它干-ER)通过抽象出削减重复表格显示,因此我可以将它作为子视图放入每个组件视图中。所以视图组件1,例如应该是这样的(“表显示”是真实抽象出在下面的代码中的一部分):我怎么可以绑定正确的服务呼叫
<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>
我的问题是, (即正确的组件)到每个组件的“表格显示”?我会在这里使用@Input,还是使用方括号绑定?
答
是的,您会在表显示组件上使用的输入,并从父组件填充:
<table-display [Data]="arrayOfData"></table-display>
其中[数据]在你的表显示定义为:
@input Data: Array<any>;
答
您可以将所需数据作为Input
传递给table-display
组件。
如果所有组件共享相同类型的结构以在表中显示数据。然后,我会建议为常用数据创建一个单独的类并传递该常用类的对象。
您可以在每个组件中编写一个映射函数,它将返回所需的数据到table-display
,或者如果它是一个简单的JSON结构,那么您可以通过它传递它。
如
比方说,有你需要的表显示,以显示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
}