2017-02-03 2 views
0

私のアングル2アプリには、さまざまなグループのデータを表示するいくつかの異なるコンポーネントがあります。異なるグループのそれぞれは、異なるAPIサービスコールを有する。ただし、異なるデータセット以外は、表形式の表示/レイアウト自体はそれぞれ同じです。私のアングル2アプリでサービスコールを修正するためのバインド

それぞれのグループのコンポーネントでは、このようなサービスコールを使用しています(これは "group1"用です)。私は私のgroup1.component.tsで私のOnInitのデータに加入していますことは:

ngOnInit() { 
    this.group1Service.getGroup() 
     .subscribe(resRecordsData => this.records = resRecordsData, 
     responseRecordsError => this.errorMsg = responseRecordsError); 
} 

、私が何をしたいかを抽象化し(すなわち作るそれドライ-ER)の重複を削減されます表形式の表示ができるので、子ビューとして各コンポーネントビューにドロップすることができます。

<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> 

私の質問があり、私は右のサービスコールをバインドする方法:だからインスタンスのコンポーネント1のためのビューは、次のようになります(「表表示すること」とは、以下のコードで抽象化だ部分です) (つまり、右のコンポーネント)を各コンポーネントの「テーブル表示」に設定しますか?ここで@Inputを使用するのか、大括弧で囲むことにしますか?

答えて

1

はい、あなたはあなたのテーブル・ディスプレイ・コンポーネントに入力を使用して、親コンポーネントからそれを埋めるだろう:

@input Data: Array<any>; 

<table-display [Data]="arrayOfData"></table-display> 

は、[データ]としてあなたのテーブル表示で定義されます

1

Inputtable-displayのデータを渡すことができます。

すべてのコンポーネントが同じタイプの構造を共有していて、表にデータを表示している場合。次に、共通のデータ用に別のクラスを作成し、その共通クラスのオブジェクトを渡すことをお勧めします。

必要なデータをtable-displayに返す各コンポーネントにマッパー関数を書き込むことができます。単純なJSON構造の場合は、それを飛ばすこともできます。

例えば

私たちは、あなたができるようになりましたそれだ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.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 

} 

} 

なしを作成 、あなたがテーブル・ディスプレイに表示する必要がある4つの属性があるとしましょうこのcommonの属性を入力します。

コンポーネントテンプレート内の0

<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 
} 
関連する問題