Angular2-自定义管道,用于 *ngfor以通过JSON值过滤结果



今天我正在尝试了解自定义管道。我可以使所有内容都可以正常工作,直到到达为Pipetransform创建ARG的部分。不管我在网上阅读什么,我似乎都无法接我。

查看plunker示例

我希望有一个可以重复使用的过滤器,可以重复使用每种卡,Visa,MC,Amex等。

*ngFor="let transaction of ('./app/api/transactions.json' | fetch | cardType:['Visa'])"

我的问题在这里,在cardtype.pipe.ts文件中:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'cardType' })
export class CardTypePipe implements PipeTransform {
    transform(value: string, args: string[]): any {
        // I can't figure out the args here...
    }
}

这是示例数据,显示了2个签证交易和1个MC。我的目标是仅在表中显示签证卡类型。我正在调用有关数据的JSON文件:

[
      {
        "cardType": "Visa",
        "amount": 153.42
      },
      {
        "cardType": "MasterCard",
        "amount": 296.11
      },
      {
        "cardType": "Visa",
        "amount": 74.57
      }
]

我的桌子:

<table class="table table-hover table-striped">
    <thead>
        <tr>
            <th>Card Type</th>
            <th class="text-xs-right">Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let transaction of ('./app/api/transactions.json' | fetch | cardType:['Visa'])">
            <td>{{ transaction.cardType }}</td>
            <td class="text-xs-right">{{ transaction.amount | currency:'USD':true }}</td>
        </tr>
    </tbody>
</table>

我认为您在模板中介绍了很多逻辑。如果将该逻辑放在其属于的控制器中,它更加优越和易于测试。

interface Transaction {
  cardType: 'Visa' | 'MasterCard';
  amount: number;
}
@Component({
  // you know the stuff...
})
class TransactionView {
  transactions: Observable<Transaction[]>;
  ngOnInit() {
    this.http.get('./app/api/transactions.json')
      .map(r => r.json())
      .filter(transaction => transaction.cardType === 'Visa')
      .subscribe(transactions => this.transactions = transactions);
  }
}

最新更新