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

查看:176
本文介绍了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依赖于Intl API,直到版本5才被所有浏览器所支持(请检查

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天全站免登陆