2017-11-02 3 views
0

私はAngular JSの初心者です。データをグループ化しているときに角2のカスタムパイプをインポートできません

私はプロジェクトでAngular 2を使用しています。

私のJSONデータは、私は状態によってデータグループを表示したい

"locations": [ 
     { 
     "id": "ASS", 
     "name": "test center", 
     "city": "Staten Island", 
     "zip": "10301", 
     "state" : "texas" 
     }, 
     { 
      "id": "ASD", 
     "name": "test center1", 
     "city": "Staten Island", 
     "zip": "10301", 
     "state" : "Florida" 
     }, 
     { 
      "id": "AAY", 
     "name": "test center2", 
     "city": "Staten Island", 
     "zip": "10301", 
     "state" : "Florida" 
     }, 
     { 
      { 
      "id": "ASD", 
     "name": "test center1", 
     "city": "Staten Island", 
     "zip": "10301", 
     "state" : "Florida" 
     } 
    ], 

の下です。

texas : <div>ASS</div> 
florida : <div>ASD</div> 
     <div>AAY</div> 
     <div>ASD</div> 

group.pipe.ts:

@Pipe({name: 'groupBy'}) 
export class GroupByPipe implements PipeTransform { 
    transform(value: Array<any>, field: string): Array<any> { 
    console.log('test'); 
    const groupedObj = value.reduce((prev, cur)=> { 
      if(!prev[cur[field]]) { 
     prev[cur[field]] = [cur]; 
    } else { 
    prev[cur[field]].push(cur); 
    } 
     return prev; 
    }, {}); 
    return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] 
    })); 

}

location.component.ts:

import {GroupByPipe} from '../group.pipe'; 
@NgModule({ 
    declarations : [GroupByPipe] 
}) 

マイエラー:

未処理プロミス拒絶:テンプレート解析エラー:

The pipe 'groupBy' could not be found (" <div class="col-sm-12 left_otr"> 
      <div class="col-md-6 col-sm-6 left" *ngFor="let [ERROR ->]item 
of pagedItems | groupBy : 'state'"> 

解決方法

+0

可能な重複[?どの角度2のグループのデータをする](https://stackoverflow.com/questions/37248580/how-to -group-data-in-angular-2) – Harshakj89

+0

tsファイルでそのデータを定義する場所を教えてください。 すでにngFor:

が使用されていますが、eror "パイプ 'groupBy'が見つかりませんでした。 –

+0

そのデータはどういう意味ですか?あなたの質問は明確ではありません。 – Harshakj89

答えて

0

ジャスト以下のコードへの配列とフィールドを合格:

transform(value: Array<any>, field: string): Array<any> { 
const groupedObj = value.reduce((prev, cur)=> { 
    if(!prev[cur[field]]) { 
    prev[cur[field]] = [cur]; 
    } else { 
    prev[cur[field]].push(cur); 
    } 
    return prev; 
}, {}); 
return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] })); 
    } 

は、パイプを使用していませんでした。

は、以下のようにように私のhtmlを更新:

<div *ngFor="let item1 of pagedItems"> 

        <h1>{{item1.key}}</h1> 

        <div *ngFor="let item of item1.value"> 
         // my logic is here. 
</div 

関連する問題