Angular - 在服务和组件中使用管道 [英] Angular - Use pipes in services and components

查看:27
本文介绍了Angular - 在服务和组件中使用管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AngularJS 中,我可以使用类似于以下的语法在服务和控制器内部使用过滤器(管道):

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

$filter('date')(myDate, 'yyyy-MM-dd');

是否可以在 Angular 中这样的服务/组件中使用管道?

Is it possible to use pipes in services/components like this in Angular?

推荐答案

和 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.

这篇关于Angular - 在服务和组件中使用管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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