如何在服务和指令脚本文件中使用 angular2 内置日期管道 [英] How to use angular2 built-in date pipe in services and directives script files

查看:18
本文介绍了如何在服务和指令脚本文件中使用 angular2 内置日期管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在服务和指令脚本文件中使用 angular2 的日期管道(不仅仅是在 HTML 中).

I need to use angular2's date pipe in services and directives script files(not only in HTML).

有人有想法吗?

由于政策限制,无法上传代码,抱歉.

Can't upload code cos some policy restrictions, sorry about that.

推荐答案

由于 CommonModule 不会将其导出为提供程序,因此您必须自己进行操作.这不是很复杂.

Since CommonModule does not export it as a provider you'll have to do it yourself. This is not very complicated.

1) 导入 DatePipe:

1) Import DatePipe:

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

2) 在模块的提供程序中包含 DatePipe:

2) Include DatePipe in your module's providers:

NgModule({
  providers: [DatePipe]
})
export class AppModule {
}

或组件的提供者:

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html',
  providers: [DatePipe]
})
export class HomeComponent {
...

3) 像任何其他服务一样将其注入到组件的构造函数中:

3) Inject it into your component's constructor like any other service:

constructor(private datePipe: DatePipe) {
}

4) 使用它:

ngOnInit() {
    this.time = this.datePipe.transform(new Date());
}

这篇关于如何在服务和指令脚本文件中使用 angular2 内置日期管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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