Angular 2 “time ago” pipe

前端 未结 8 1456
余生分开走
余生分开走 2020-12-08 04:56

I am trying to create a \'time ago\' pipe for my Angular 2 application.

It should transform a date to a string such as \'5 minutes ago\' or \'60 seconds ago\'. It wo

8条回答
  •  甜味超标
    2020-12-08 05:00

    You need to update the 'date' reference to trigger Angular2's change detection, with a setTimeout(()=>this.date=new Date(), period) for instance, as Thierry pointed out.

    Do you really need an update every second? Updating every 60 seconds might be good enough depending on your use case, and could display 'just now' or 'less than a minute ago' for the first 60 seconds.

    But if you really want the seconds, you only need to update every seconds for the first 60 seconds. The setTimeout(1000) can then become setTimeout(60000), to minimizes overhead.

提交回复
热议问题