JSON

angular2系列教程(六)升级装备、pipe(2)

字号+ 作者:H5之家 来源:H5之家 2017-05-29 09:06 我要评论( )

src/app/stateful/hero-list.component.ts import {Component} from 'angular2/core';import {FetchJsonPipe} from './fetch-json.pipe';@Component({ selector: 'hero-list', template: `h4Heroes from JSON File/

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

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 易语言json操作例程源码

    易语言json操作例程源码

    2017-05-29 10:02

  • 解析XML和JSON内容的一点技巧的实例代码分享

    解析XML和JSON内容的一点技巧的实例代码分享

    2017-05-26 15:01

  • [BTS]教程:从0.9.3c输出key.json文件中删除无用私钥

    [BTS]教程:从0.9.3c输出key.json文件中删除无用私钥

    2017-05-26 14:00

  • php读取json文件的相关文章,教程,源码

    php读取json文件的相关文章,教程,源码

    2017-05-24 14:00

网友点评
r