本文翻译自:Angular - Use pipes in services and components

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this: 在AngularJS中,我可以使用类似于以下语法的服务和控制器内部使用过滤器(管道):

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

Is it possible to use pipes in services/components like this in Angular? 是否可以在Angular中在服务/组件中使用管道?


#1楼

参考:https://stackoom.com/question/2NSlx/Angular-在服务和组件中使用管道


#2楼

This answer is now outdated 这个答案现在已经过时了

recommend using DI approach from other answers instead of this approach 建议使用其他答案中的DI方法代替此方法

Original answer: 原始答案:

You should be able to use the class directly 您应该可以直接使用该类

new DatePipe().transform(myDate, 'yyyy-MM-dd');

For instance 例如

var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');

#3楼

As usual in Angular, you can rely on dependency injection: 像在Angular中一样,您可以依赖于依赖项注入:

import { DatePipe } from '@angular/common';class MyService {constructor(private datePipe: DatePipe) {}transformDate(date) {return this.datePipe.transform(date, 'yyyy-MM-dd');}
}

Add DatePipe to your providers list in your module; DatePipe添加到模块中的提供者列表中; if you forget to do this you'll get an error no provider for DatePipe : 如果您忘记执行此操作,则会收到错误, no provider for DatePipe

providers: [DatePipe,...]

Update Angular 6 : Angular 6 now offers pretty much every formatting functions used by the pipes publicly. 更新Angular 6 :Angular 6现在提供了管道公开使用的几乎所有格式化功能。 For example, you can now use the formatDate function directly. 例如,您现在可以直接使用formatDate函数。

import { formatDate } from '@angular/common';class MyService {constructor(@Inject(LOCALE_ID) private locale: string) {}transformDate(date) {return formatDate(date, 'yyyy-MM-dd', this.locale);}
}

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 5之前 :警告,尽管DatePipe依赖于Intl API,直到版本5为止(并非所有浏览器都支持该版本 )(请检查兼容性表 )。

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. 如果使用的是较旧的Angular版本,则应将Intl polyfill添加到项目中,以避免出现任何问题。 See this related question for a more detailed answer. 请参阅此相关问题以获取更详细的答案。


#4楼

Yes, it is possible by using a simple custom pipe. 是的,可以使用简单的自定义管道。 Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file. 使用自定义管道的优点是,如果将来需要更新日期格式,则可以去更新单个文件。

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';@Pipe({name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {transform(value: string) {var datePipe = new DatePipe("en-US");value = datePipe.transform(value, 'MMM-dd-yyyy');return value;}
}{{currentDate | dateFormatPipe }}

You can always use this pipe anywhere , component, services etc 您随时可以在任何位置,组件,服务等地方使用此管道

For example 例如

export class AppComponent {currentDate : any;newDate : any;constructor(){this.currentDate = new Date().getTime();let dateFormatPipeFilter = new dateFormatPipe();this.newDate = dateFormatPipeFilter.transform(this.currentDate);console.log(this.newDate);
}

Dont forget to import dependencies. 不要忘记导入依赖项。

import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'

Custom Pipe examples and more info 自定义管道示例和更多信息


#5楼

If you don't want do 'new myPipe()' because you're injecting dependencies to pipe, you can inject in component like provider and use without new. 如果由于要注入要依赖的管道而不想执行“ new myPipe()”,则可以注入诸如provider之类的组件,而无需使用new。

Example: 例:

// In your component...import { Component, OnInit } from '@angular/core';
import { myPipe} from './pipes';@Component({selector: 'my-component',template: '{{ data }}',providers: [ myPipe ]
})
export class MyComponent() implements OnInit {data = 'some data';constructor(private myPipe: myPipe) {}ngOnInit() {this.data = this.myPipe.transform(this.data);}
}

#6楼

Other answers don't work in angular 5? 其他答案在角度5中不起作用吗?

I got an error because DatePipe is not a provider, so it cannot be injected. 我收到一个错误消息,因为DatePipe不是提供程序,因此无法注入它。 One solution is to put it as a provider in your app module but my preferred solution was to instantiate it. 一种解决方案是将其作为应用程序模块中的提供程序,但我首选的解决方案是实例化它。

Instantiate it where needed: 在需要的地方实例化它:

I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174 我查看了DatePipe的源代码以了解其如何获取语言环境: https : //github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174

I wanted to use it within a pipe, so my example is within another pipe: 我想在管道中使用它,所以我的示例在另一个管道中使用:

import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
import { DatePipe } from '@angular/common';@Pipe({name: 'when',
})
export class WhenPipe implements PipeTransform {static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));datePipe: DatePipe;constructor(@Inject(LOCALE_ID) private locale: string) {this.datePipe = new DatePipe(locale);}transform(value: string | Date): string {if (typeof(value) === 'string')value = new Date(value);return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')}
}

The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly. 此处的关键是从angular的核心导入Inject和LOCALE_ID,然后进行注入,以便将其提供给DatePipe以正确实例化它。

Make DatePipe a provider 使DatePipe成为提供程序

In your app module you could also add DatePipe to your providers array like this: 在您的应用模块中,您还可以将DatePipe添加到您的provider数组中,如下所示:

import { DatePipe } from '@angular/common';@NgModule({providers: [DatePipe]
})

Now you can just have it injected in your constructor where needed (like in cexbrayat's answer). 现在,您可以将它注入所需的构造函数中(例如cexbrayat的答案)。

Summary: 摘要:

Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself. 无论哪种解决方案都有效,我不知道哪个角度会认为最“正确”,但我选择手动实例化它,因为angular本身不提供日期管道。

Angular-在服务和组件中使用管道相关推荐

  1. SpringCloud_004_SpringCloud服务发现组件原理介绍

    SpringCloud_004_SpringCloud服务发现组件原理介绍 技术交流qq群,交流起来方便一些:170933152 1.如何解决硬编码问题? 上次咱们说到,硬编码问题 比如: 服务发现组 ...

  2. anguar4 共享服务在多个组件中数据通信

    应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果.这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果, ...

  3. 业务中台管理系统、业务中台架构、接口类服务、模型类服务、界面类服务、组件类服务、服务架构、中后台、服务审核、AI服务、位置服务、行业场景服务、企业中台、接口配置、模型配置、数据处理、结构化数据、数据源

    业务中台管理系统.业务中台架构.接口类服务.模型类服务.界面类服务.组件类服务.服务架构.中后台.服务审核.AI服务.位置服务.行业场景服务.企业中台.接口配置.模型配置.数据处理.结构化数据.数据源 ...

  4. Angular定义服务-Learn By Doing

    1.服务(Service)介绍 Angular services are substitutable objects that are wired together using dependency ...

  5. Angular的后院:组件依赖关系的解决

    by Dor Moshe 通过Dor Moshe Angular的后院:解决 组件依赖关系 (Angular's Backyard: The Resolving of Components Depen ...

  6. angular 模块构建_如何使用Angular和服务人员构建无需Internet即可运行的网站

    angular 模块构建 by Tomiwa 通过Tomiwa 如何使用Angular和服务人员构建无需Internet即可运行的网站 (How to build websites that work ...

  7. 手牵手教你使用ngComponentOutlet创建一个支持自定义插入子组件的angular公共搜索表单组件

    目录 雏形 主体 逻辑完善 使用公共表单组件 总结 最后 这几天笔者所接手的angular项目需要重新封装一个公共表单组件,由于之前封装的表单组件自由度不够,每出现一种新的类型的特殊输入框就需要在公共 ...

  8. 关于Angular 4 + ng-zorro 使用过程中遇到的问题

    写在前面 由于现在网络上Angular 4的相关技术文档不是很充分,我写出这个采坑的记录文档,一方面是想给自己在项目中遇到的各种问题与个人的理解记录下来,另一方面也想着某些坑大家可能也会遇到,也可以给 ...

  9. 使用模式创建一个面向服务的组件中间件

    引言 在本文中,您将了解面向服务的组件中间件在用于资源有限的语音设备时,在设计阶段所应用的模式.它涵盖了项目的问题上下文,并被看成是一组决定因素,是对相关体系结构远景的一个简要概括.您还会得到一份描述 ...

最新文章

  1. 赛码浪潮笔试题库软件实施岗位_2020年浪潮软件类笔试题
  2. 【UGV】32版UGV原理图
  3. centos7配置静态IP
  4. django-学习索引1908版
  5. 使用jupyter计算正态分布_专栏 | 基于 Jupyter 的特征工程手册:数据预处理(三)...
  6. paping使用来测试联通网站由于tcp协议导致的无法通信问题超时问题
  7. LINQ to CSV,一种类型安全,动态的高性能方法
  8. android动态service,Android基础回顾之Service
  9. [转载] OpenCV-Python 图像处理(二):图像的读取、显示与保存
  10. JAVA(二)异常/包及访问权限/多线程/泛型
  11. 中职计算机教学随笔800字,职高教育工作随笔
  12. 力扣-多线程专项(一)(按序打印、交替打印、打印零与奇偶数)
  13. win10安装Hive3.0.0
  14. Linux下读取RFID卡号(C串口编程)
  15. 训练人物和摩托车的yolov4-tiny模型教程
  16. 前端和Java,学哪个好?
  17. Filler Cell 与 Metal Fill差异
  18. 连载《国培计划》骨干教师的研修日志之七:N个老师的日志
  19. MSF外网渗透+shellcode免杀
  20. 【必须知道的职场情商训练7法】

热门文章

  1. CyclicBarrier和CountDownLatch区别
  2. volatile 和 sig_atomic_tlinux
  3. Java 类不可被继承的几种方法
  4. 曹新雨-2020年目标
  5. Kotlin返回值Unit、Nothing与Any
  6. android studio 如何提示方法的用法
  7. 行业 平均年龄_2019中国“新生力”白皮书:平均年龄35岁,千万资产家庭达198万户!...
  8. PHP学习笔记-文件操作1
  9. Java知识系统回顾整理01基础04操作符07Scanner
  10. OWASP top 10 (2017) 学习笔记--失效的身份验证