今天,我们要讲的是angualr2的pipe这个知识点。

例子

这个例子包含两个pipe,一个是stateful,一个是stateless,是直接复制官方的例子(最新的官网文档已经将其改为了pure和impure,并移除了面向对象的比喻,个人认为较为准确,请以最新的官网文档为参考!)。

源代码

stateless pipe

pipe就是ng1中的filter。先看看内建pipe吧:

  • currency
  • date
  • uppercase
  • json
  • limitTo
  • lowercase
  • async
  • decimal
  • percent

无需编写直接用!今天说了太多“直接用”哈哈!

pipe分为两种,一种是stateful,一种是stateless。我们先说stateless,stateless就是使用纯函数,不记住任何数据,也不会带来任何副作用。DatePipe就是stateless,我们再写个计算次方的pipe吧:

app/stateless/exponential-strength.pipe.ts

import {Pipe, PipeTransform} from 'angular2/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 |  exponentialStrength:10}}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, args: string[]) : any {
    return Math.pow(value, parseInt(args[0] || '1', 10));
  }
}

很简单,计算某个值的某次方,{{ 2 | exponentialStrength:10}}就是2的10次方。

写个模板测试下:

app/stateless/power-booster.component.ts

import {Component} from 'angular2/core';
import {ExponentialStrengthPipe} from './exponential-strength.pipe';
@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>
    <p>
      Super power boost: {{2 | exponentialStrength: 10}}
    </p>
  `,
  pipes: [ExponentialStrengthPipe]
})
export class PowerBooster { }

注入pipes: [ExponentialStrengthPipe],然后直接用!

stateful pipe

先看一个stateful pipe的例子吧:

app/stateful/fetch-json.pipe.ts

declare var fetch;
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
  name: 'fetch',
  pure: false
})
export class FetchJsonPipe  implements PipeTransform {
  private fetchedValue: any;
  private fetchPromise: Promise<any>;
  transform(value: string, args: string[]): any {
    if (!this.fetchPromise) {
      this.fetchPromise = fetch(value)
        .then((result: any) => result.json())
        .then((json: any)   => this.fetchedValue = json);
    }
    return this.fetchedValue;
  }
}

我们干了这些事:

  1. 将pure参数设为false
  2. 在成员函数transform中,执行fetch请求,将结果赋给this.fetchedValue = json,最后返回结果
  3. 如果this.fetchPromise这个成员变量已经被定义过,则直接返回成员变量fetchedValue

写个模板测试下:

app/stateful/hero-list.component.ts

import {Component} from 'angular2/core';
import {FetchJsonPipe} from './fetch-json.pipe';
@Component({
  selector: 'hero-list',
  template: `
    <h4>Heroes from JSON File</h4>
    <div *ngFor="#hero of ('/assets/heroes.json' | fetch) ">
      {{hero.name}}
    </div>
    <p>Heroes as JSON:
    {{'/assets/heroes.json' | fetch | json}}
    </p>
  `,
  pipes: [FetchJsonPipe]
})
export class HeroListComponent {
  /* I've got nothing to do ;-) */
}

'/assets/heroes.json'是我自己编写的json文件,放在了assets里面,因为这是webpack的静态文件地址。

结果:

特性解读

Stateful pipes are conceptually similar to classes in object-oriented programming. They can manage the data they transform. A pipe that creates an HTTP request, stores the response and displays the output, is a stateful pipe.

这是官方对statefule pipe的描述。说是能够创建http请求,存储响应,显示输出的pipe就是stateful pipe。那么stateless pipe不能做这些事吗?我好奇的在stateless pipe中尝试做http请求:

declare var fetch;
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
  name: 'fetch'
})
export class FetchJsonPipe  implements PipeTransform {
  transform(value: string, args: string[]): any {
    fetch(value)
        .then((result: any) => result.json())
        .then((json: any)   =>  json);
  }
}

结果什么都输出不了!说明当我们需要使用http的时候,或者处理异步的时候,需要使用stateful pipe。这两个pipe的区别也正是“函数式编程”和“面向对象”的区别——有无状态。在最新的官网文档中,已经把这两个pipe改为了pure和impure,而且没有提到面向对象编程。个人认为最新文档的观点较为准确!使用“有无状态“来区别函数式编程和面向对象编程不够准确!


教程源代码及目录

如果您觉得本博客教程帮到了您,就赏颗星吧!

https://github.com/lewis617/angular2-tutorial

angular2系列教程(六)两种pipe:函数式编程与面向对象编程的更多相关文章

  1. angular2系列教程(十)两种启动方法、两个路由服务、引用类型和单例模式的妙用

    今天我们要讲的是ng2的路由系统. 例子

  2. C#微信公众号开发系列教程六(被动回复与上传下载多媒体文件)

    微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...

  3. [转]Android Studio系列教程六--Gradle多渠道打包

    转自:http://www.stormzhang.com/devtools/2015/01/15/android-studio-tutorial6/ Android Studio系列教程六--Grad ...

  4. Android Studio系列教程六--Gradle多渠道打包

    Android Studio系列教程六--Gradle多渠道打包 2015 年 01 月 15 日 DevTools 本文为个人原创,欢迎转载,但请务必在明显位置注明出处!http://stormzh ...

  5. CRL快速开发框架系列教程六(分布式缓存解决方案)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  6. angular2系列教程(一)hello world

    今天我们要讲的是angular2系列教程的第一篇,主要是学习angular2的运行,以及感受angular2的components以及模板语法. 例子 这个例子非常简单,是个双向数据绑定.我使用了官网 ...

  7. 黄聪:Microsoft Enterprise Library 5.0 系列教程(六) Security Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(六) Security Application Block 开发人员经常编写需要安全功能的应用程序.这些应用程序 ...

  8. webpack4 系列教程(六): 处理SCSS

    这节课讲解webpack4中处理scss.只需要在处理css的配置上增加编译scss的 LOADER 即可.了解更多处理css的内容 >>> >>> 本节课源码 & ...

  9. 创建对象的两种方法: new 和 面向对象(对象字面量)及对象属性访问方法

    创建对象的两种方法: new 和 面向对象(对象字面量)用 new 时:var o = new Object();o.name = "lin3615";alert(o.name); ...

随机推荐

  1. DailyTick 开发实录 —— 开始

    2009 年我读了李笑来老师的<把时间当朋友>,知识了柳比歇夫的时间记录法.当时激动坏了,马上动手实践起来.一开始的时候,是用一个小本子,走到哪儿都带着.完成一件事,就记录一下花费的时间. ...

  2. 【原】实时渲染中常用的几种Rendering Path

    [原]实时渲染中常用的几种Rendering Path 本文转载请注明出处 —— polobymulberry-博客园 本文为我的图形学大作业的论文部分,介绍了一些Rendering Path,比较简 ...

  3. 不懂CSS的后端难道就不是好程序猿?

    由于H5在移动端的发展如日中天,现在大部分公司对高级前端需求也是到处挖墙角,前端薪资也随之水涨船高,那公司没有配备专用的前端怎么办呢? 作为老板眼中的“程序猿” 前端都不会是非常无能的表现,那作为后端 ...

  4. c# Enumerable中Aggregate和Join的使用

    参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/asp.net-core-environment.html http://www.yuanjiaochen ...

  5. BPM应用开发解决方案分享

    一.需求分析企业整体管理是一个完整的体系,如果 把这个体系比做一个拼图,企业信息化通过各个业务系统覆盖了一部分业务. 企业通过采购实施通用软件的方式,覆盖了企业的核心业务和专业化业务然而系统只满足了部 ...

  6. 熊乐:H3 BPM为加速企业流程管理提供源动力

    近日,在北京·金隅喜来登酒店,H3 BPM以"让天下没有难用的流程"为主题,正式发布H3 BPM10.0版本.全新的业务流程管理系统在易用性方面大大提升,并且全面支持Java与.N ...

  7. 手动导入swift三方danielgindi/Charts到OC工程中教程

    1.到github网址上下载zip压缩包https://github.com/danielgindi/Charts 2.然后将解压后的文件夹整个拖到自己的工程文件夹下(很多教程只让拖xcodeproj ...

  8. React Native环境配置之Windows版本搭建

    接近年底了,回想这一年都做了啥,学习了啥,然后突然发现,这一年买了不少书,看是看了,就没有完整看完的.悲催. 然后,最近项目也不是很紧了,所以抽空学习了H5.自学啃书还是很无趣的,虽然Head Fir ...

  9. 设计模式之工厂模式VS抽象工厂

    一.工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的. 工厂模式在<Java与模式>中分为三类:1)简单工厂模式(Simple Factor ...

  10. Ubuntu下配置apache开启https

    一.HTTPS简述随着网络的日常,信息安全越来越重要,传统的网站都是http协议明文传输,而HTTPS协议是由SSL+HTTP协议构建的可进行加密传输.身份认证的网络协议,比http协议安全. 那ht ...