angular2,Pipe管道初使用。

以前都知道angular2有管道这个东西,不过,由于没有使用的必要,也就没怎么看。

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

我的做法是在本地新建一个Object对象result。然后,在数据传过来的时候,赋值到result。

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

{{ result.property }}

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

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

result是undefined,所以找不到。

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

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

但是,属性差不多有40多个,我岂不是得写40多次!肯定不行。

后来,想到了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' }}
原文地址:https://www.cnblogs.com/hcy1994/p/6612962.html