且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular - 在服务和组件中使用管道

更新时间:2022-12-20 15:39:04

和 Angular 一样,你可以依赖依赖注入:

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

DatePipe 添加到模块中的提供者列表中;如果你忘记这样做,你会得到一个错误 no provider for DatePipe:

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

providers: [DatePipe,...]

更新 Angular 6:Angular 6 现在提供了管道公开使用的几乎所有格式化功能.例如,您现在可以直接使用 formatDate 函数.>

Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

import { formatDate } from '@angular/common';

class MyService {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

Angular 5 之前:请注意,DatePipe 在版本 5 之前一直依赖于 Intl API,并非所有浏览器都支持该 API(检查 兼容性表).

Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

如果您使用的是较旧的 Angular 版本,您应该将 Intl polyfill 添加到您的项目中以避免出现任何问题.请参阅此 相关问题以获得更详细的答案.

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.