I have a goal in mind and here is what I want to achieve:
Imagine having a model for a post that includes a JavaScript Date object. Now, I'd like to display the date in a personalized, easy-to-read format that shows an offset from the current time (like "just now", "about one hour ago", "about two hours ago" etc.).
Although new to TypeScript and Angular2, my research suggests that the most elegant solution would involve creating a custom pipe like this:
@Pipe({name: 'hrTime'})
export class HrTimePipe implements PipeTransform {
constructor(private translate: TranslateService) {
}
transform(val: Date): string {
// Approximate check if the date was around an hour ago
let now: Date = new Date();
now.setMinutes(now.getMinutes() - 90);
if (val > now) {
return this.translate.instant("about_1_h_ago");
}
}
}
The issue with this method is that the TranslateService's instant()
function may not ensure that the translation file is loaded when the pipe is created or used. As a result, my current custom pipe only displays the translation key (as instant()
cannot locate the translation).
When dealing with longer time intervals (such as more than a day ago), my pipe should switch to using the date format pipe internally instead of returning a translation key that needs to be piped into translate
.
Any suggestions on this matter? Is employing a custom pipe the correct approach for achieving my goal?
Thank you!