让管道在angular中自我刷新



我有静态时间戳从后端,我想刷新管道每1秒从现在得到日期这是我的管子

import { Pipe, PipeTransform } from '@angular/core';
import moment from 'moment';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {
transform(date: string): string {
return moment.utc(date, 'X').local().format('DD-MM-YYYY h:mm:ss a');
}
}

在这个例子中它只是将时间戳转换成这种格式,我想保持日期更新怎么做呢?

你应该返回一个可观察对象,并使用asyncPipe。

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import { interval, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {
transform(date: string): Observable<string> {
return interval(1000).pipe(map(() => { return moment().format('DD-MM-YYYY h:mm:ss a') }));
}
}

你应该这样使用它:{{ 'param' | dateFormat | async}}

我想你只需要刷新你的时间,每秒钟传入管道?

currentTime$ = Observable.interval(1000).pipe(map(() => { return new Date() } ))

最新更新