angular管道pipe

111 阅读1分钟

如其名字,模板数据经过pipe在展示在界面

  • 优点
    • 性能相对方法更好。注册在更模板也能全局使用
    • 读性和表达力:管道提供了一种更清晰和表达力更强的方式来转换数据
    • 允许将多个转换操作链接在一起,形成管道链。这样可以轻松实现复杂的数据转换逻辑,而无需在组件中嵌套多个方法调用。
    • 纯函数和无状态:管道被设计为纯函数,不会对外部状态产生副作用,并且给定相同的输入总是返回相同的输出。这使得管道更容易测试和调试,并且可以帮助避免一些常见的错误。
  • 缺点
    • 非全局pipe不好组织文件,每个模块下放置一个pipe文件有些浪费。

同步管道

  • 定义:实现PipeTransform接口类
  • 使用参数: 参数通过:隔开。 arr | filterOptions: 'args' : 'args2'
    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({
      name: 'filterOptions',
    })
    export class FilterOptionsPipe implements PipeTransform {
      transform(options: any[], filterValue: any, filterKey: string): any[] {
        if (!filterValue) {
          return [];
        }
        return options.filter((option) => option[filterKey] === filterValue);
      }
    }
    

异步管道

在@component中使用(组件中)

  • 通过依赖注入的方式
// angular内置管道(格式化货币值)
import { CurrencyPipe } from '@angular/common';
export class YourComponent { 
    constructor(private currencyPipe: CurrencyPipe) { 
        // 使用CurrencyPipe来格式化货币值 
        const formattedPrice = this.currencyPipe.transform(123.45, 'USD', 'symbol', '1.2-2'); 
        // 输出格式化后的货币值
        console.log(this.formattedPrice);  
    } 
}
  • 使用静态方法,因为管道其实也是一个实现transform接口的类
import { CurrencyPipe } from '@angular/common';
export class YourComponent { 
    formattedPrice: string; constructor() { 
        // 使用CurrencyPipe.transform()方法来格式化货币值 
        const formattedPrice = CurrencyPipe.transform(123.45, 'USD', 'symbol', '1.2-2');
        // 输出格式化后的货币值
        console.log(this.formattedPrice);
    } 
}