src/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。
教程源代码及目录如果您觉得本博客教程帮到了您,就赏颗星吧!
https://github.com/lewis617/angular2-tutorial