【问题标题】:Angular2 - Custom Pipe for *ngFor to filter results by JSON ValueAngular2 - *ngFor 的自定义管道按 JSON 值过滤结果
【发布时间】:2017-05-15 00:35:03
【问题描述】:

今天我正在尝试了解自定义管道。我可以让一切正常工作,直到我到达为 PipeTransform 创建参数的部分。无论我在网上阅读什么内容,我似乎都无法理解我离开的地方。

View Plunker Example

我希望有一个过滤器可以重复用于每种卡类型、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 次 Visa 交易和 1 次 MC 的示例数据。我的目标是只在表格中显示 VISA 卡类型。我正在为数据调用 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>

【问题讨论】:

    标签: json angular typescript angularjs-filter


    【解决方案1】:

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

    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);
      }
    }
    

    【讨论】:

    • 感谢您的回复,莱昂。因为我正在学习,所以我希望了解如何通过使用自定义管道来专门解决问题。我觉得我很接近但错过了最后一块。我认为您的 .filter 可能会将我带到某个地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多