如何扩展angular2 DatePipe [英] How to extend angular2 DatePipe

查看:57
本文介绍了如何扩展angular2 DatePipe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到angular2.beta15(包括),以下代码都可以正常工作:

Up to angular2.beta15 (including) the following code was working fine:

@Pipe({
  name: 'isoDate'
})
export class ISODatePipe extends DatePipe implements PipeTransform {
  transform(isoDate: string, args: any[]): string {
    return super.transform(new Date(isoDate), args);
  }
}

即使在我调整管道语法之后,在RC1上它也不再起作用:

On RC1 its not working anymore, even after I adjusted pipes syntax:

@Pipe({
  name: 'isoDate'
})
export class ISODatePipe extends DatePipe implements PipeTransform {
  transform(isoDate: string, pattern?: string): string {
    const date = new Date(isoDate);
    return super.transform(date, pattern);
  }
}

我在浏览器中看到的消息如下:The pipe 'isoDate' could not be found.

The message i see in the browser is following: The pipe 'isoDate' could not be found.

如果我删除了extends部分并返回了一些字符串,它将再次起作用.

If I remove the extends part and return some string - it works again.

发生了什么变化?

P.S.

当前将其更改为

@Pipe({ name: 'isoDate' })
export class ISODatePipe implements PipeTransform {
  private datePipe: DatePipe = new DatePipe();

  transform(isoDate: string, pattern?: string): string {
    const date = new Date(isoDate);
    return this.datePipe.transform(date, pattern);
  }
}

它可以工作,但是看起来有点奇怪.

It works, but looks a bit strange.

推荐答案

发生了什么变化?

显然,DatePipe类现在具有构造函数

Apparantely DatePipe class has now constructor

constructor(@Inject(LOCALE_ID) private _locale: string) {} 因此您可以通过 LOCALE_ID 作为参数:

constructor(@Inject(LOCALE_ID) private _locale: string) {} so you can pass LOCALE_ID as parameter:

const datePipe = new DatePipe();

在编译时指定本地ngc --locale=en-US LOCAL_ID将传递给DatePipe构造函数.

When you compile specifying local ngc --locale=en-US The LOCAL_ID get passed to the DatePipe constructor.

这篇关于如何扩展angular2 DatePipe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆