angular2,Pipe管道初使用。

之前都知道angular2有管道这个东西,不过,因为没有使用的必要,也就没怎么看。javascript

今天,作页面,接收点击查询传来的数据,而后,显示出来。html

个人作法是在本地新建一个Object对象result。而后,在数据传过来的时候,赋值到result。java

可问题出在,初始化显示模板时,我使用了 angular2

{{ result.property }}

  的数据绑定方式,可是,这种方式在 component 初始化的时候,报错了。spa

说 result.property 属性找不到。其实,想想也明白,初始化html的时候,code

result是undefined,因此找不到。component

我想了其中一种方法,就是在 result 初始化的时候,用这种形式orm

result = {
  property1: 'null',
  property2: 'null',
......    
}

可是,属性差很少有40多个,我岂不是得写40屡次!确定不行。htm

后来,想到了angular2有管道这个东西,而后,看了下文档,以为能用管道解决我这问题。对象

写个管道判断就好了!

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'juedeProperty'})
export class JudgePropertyPipe implements PipeTransform {
  transform(obj: Object, pro: string): any {
    if (obj != undefined) {
      return obj[pro];
    } else {
      return 'null';
    }
  }
}

管道含义,传入一个obj: Object类型,传入一个pro: string类型,

若是obj为空,就返回 'null',

若是obj不为空,那么就将属性值返回。

最后,将 JuedgePropertyPipe 导入到 module,

而后,module中的全部组件就都能使用了。

{{ result | JudgeProperty: 'property1' }}
相关文章
相关标签/搜索