我试图创建一个带有日期时间戳的管道,并返回自那时起的时间。
我有以下管道,它返回一次持续时间,但是我需要这个管道每秒递增以产生一个计时器效果:
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'duration' })
export class DurationPipe implements PipeTransform{
transform(value: any){
var now = moment(new Date());
var end = moment(value);
var dif = moment.duration(now.diff(end));
var toReturn = [];
if(("00" + dif.hours()).slice(-2) != "00"){
toReturn[toReturn.length] = ("00" + dif.hours()).slice(-2);
}
toReturn[toReturn.length] = ("00" + dif.minutes()).slice(-2);
toReturn[toReturn.length] = ("00" + dif.seconds()).slice(-2);
return toReturn.join(':');
}
}
我看过异步管道,但似乎无法按照我的意愿运行它。
任何解决方案?
答案 0 :(得分:1)
Pipe组件从模板传递值并转换新值。您不应该使用Pipe来计算持续时间并定期更新到视图,因为除非值已更改,否则管道不会自行更新。 (管道默认都是纯管道!)
我认为你应该在你的组件中实现它,而不是在Pipe中实现它。
答案 1 :(得分:1)
从@Hinrich留下的评论中汲取灵感
我决定将当前时间传递给管道。更改此值将触发管道更改。这允许在我的应用程序中重复使用两次计算差异的逻辑。
为了使它显示为计时器,我设置了一个超时功能,用于更新正在使用管道的组件中的当前时间参数
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'duration'})
export class DurationPipe implements PipeTransform{
transform(value: any, now: any){
var end = moment(value);
var dif = moment.duration(now.diff(end));
var toReturn = [];
if(("00" + dif.hours()).slice(-2) != "00"){
toReturn[toReturn.length] = ("00" + dif.hours()).slice(-2);
}
toReturn[toReturn.length] = ("00" + dif.minutes()).slice(-2);
toReturn[toReturn.length] = ("00" + dif.seconds()).slice(-2);
return toReturn.join(':');
}
}
然后在组件中
@Component({
moduleId: module.id,
templateUrl: 'pending.template.html',
styleUrls: ['../orders.scss']
})
export class PendingComponent implements OnInit {
orders: any[];
now = moment(new Date());
constructor(private route: ActivatedRoute, private router: Router, private orderService: OrderService, public dialog: MdDialog ){}
ngOnInit() {
Observable.interval(1000).subscribe(x=>{
this.now = moment(new Date());
})
}
}
,html为
{{order.createdAt | duration:now}}