How to use angular2 built-in date pipe in services and directives script files [duplicate]

柔情痞子 提交于 2019-11-27 03:03:12

问题


This question already has an answer here:

  • How to use a pipe in a component in Angular 2? 3 answers

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

Does anyone have ideas?

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


回答1:


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

1) Import DatePipe:

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

2) Include DatePipe in your module's providers:

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

or component's providers:

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

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

constructor(private datePipe: DatePipe) {
}

4) Use it:

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



回答2:


Try something like this:

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

Hope this will help.



来源:https://stackoverflow.com/questions/41280149/how-to-use-angular2-built-in-date-pipe-in-services-and-directives-script-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!