如何对来自管道的数据应用条件

时间:2019-01-16 12:57:12

标签: angular typescript

我实现了一个获取两个值并找到它们之间持续时间的管道,如果持续时间小于1天,它以天为单位计算持续时间,它返回0,但是我不想在这种情况下显示0如果持续时间少于一天,则显示“最近”。

HTML

     <div>{{firstdate | myPipe : agent.lastUpdated}} d ago</div>

pipe.ts

import { PipeTransform, Pipe } from "@angular/core";
@Pipe({
name: 'myPipe',
pure: true

  })
 export class durationPipe implements PipeTransform{

transform(firstDate:any , secondDate:any):any{
   if(!firstDate || !secondDate){
       return firstDate;
   }

   const dropdt:any = new Date(firstDate);
  const pickdt:any = new Date(secondDate);
      const time = +((firstDate - secondDate) / (24 * 3600 * 1000));
    //   console.log("this is currentTime "+firstDate);
    //   console.log("this is userTime "+secondDate);
     const a = time.toString().split('.',1);
    // console.log("time is "+a);
      return a;
  }
}

1 个答案:

答案 0 :(得分:1)

执行此类任务的原因有几种。

第一个比较快,但是由于绑定相对较多,所以性能很差:

Read

我建议您创建两个管道:一个用于计算天数差异,另一个用于正确显示。

OnRxBuf

所以用法很简单:

<div>
  <span *ngIf="firstdate | myPipe : agent.lastUpdated">
    {{firstdate | myPipe : agent.lastUpdated}} d ago
  </span>
  <span *ngIf="!(firstdate | myPipe : agent.lastUpdated)">
    recently
  </span>
</div>