如何在服务和指令脚本文件中使用 angular2 内置日期管道

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

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

有没有人有想法?

由于某些政策限制,无法上传代码,对此深感抱歉。

在你的组件中

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

如果您使用的是Angular2、4版本,试试

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

如果您使用的是 Angular 6 及更高版本

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

希望这会有所帮助。

由于 CommonModule 不会将其导出为提供者,因此您必须自己做。这个不是很复杂。

1) 导入 DatePipe:

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

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

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

或组件的供应商:

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

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

constructor(private datePipe: DatePipe) {
}

4) 使用它:

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