0

first, this is what I would like to accomplish:

Let's say I have a model for a posting that contains a js Date object. Now, I would like to render the date in a custom, human readable format that does not show a date and time, but rather an offset from now (i.e. "just now", "about one hour ago", "about two hours ago" etc.).

I am new to both, TypeScript and angular2, but from what I read so far, the most elegant approach would be to use a custom pipe like that:

@Pipe({name: 'hrTime'})
export class HrTimePipe implements PipeTransform {

    constructor(private translate: TranslateService) {

    }

    transform(val: Date): string {

        // Roughly check if that date is about one hour ago
        let now: Date = new Date();
        now.setMinutes(now.getMinutes() - 90);
        if (val > now) {
            return this.translate.instant("about_1_h_ago");
        }
    }
}

The problem with this approach is that TranslateService's instant() method doesn't make sure the translation file is loaded at the time this pipe is constructed or used. Therefore, my custom pipe currently just returns my translation key (since instant() doesn't find my translation).

For larger timegaps (i.e. more than a day ago), my pipe should internally just use the date format pipe, so returning a translation key that has to be piped into translate isn't really an option.

Do you have any suggestions? Is using a custom pipe the right approach for what I would like to accomplish?

Thanks!

4

2 回答 2

0

如果你不关心有外部依赖,为什么不使用矩管,你有这个工具在 Angular 2 https://github.com/urish/angular2-moment

于 2017-03-08T11:39:16.813 回答
0

你可以把它变成一个不纯的管道并返回一个 Observable。这样,您可以将管道链接到async管道并使其无缝工作。

这样你就会有三种情况我认为: - 时间间隔很大:立即解决日期 - 时间间隔很小,翻译已经加载:立即翻译和解决 - 时间间隔很小,翻译还没有准备好然而:等待翻译文件加载,然后用正确的翻译解决

于 2017-03-08T11:24:13.277 回答