在AngularJS中,我能够在服务和控制器中使用过滤器(管道),使用类似于下面的语法:

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

在Angular中,可以在服务/组件中像这样使用管道吗?


当前回答

如果想在组件中使用自定义管道,可以添加

@Injectable({
  providedIn: 'root'
})

注释到自定义管道。 然后,您可以将其作为一项服务使用

其他回答

如果您不想使用新的mpipe(),因为您正在向管道注入依赖项,您可以注入像provider这样的组件并使用而不使用new。

例子:

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);
  }
}

您可以使用formatDate()来格式化服务或组件中的日期。 语法:

    formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string

从普通模块导入formatDate(),如下所示:

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

在课堂上像这样使用它,

    formatDate(new Date(), 'MMMM dd yyyy', 'en');

你也可以使用angular提供的预定义格式选项,如下所示:

    formatDate(new Date(), 'shortDate', 'en');

你可以在这里看到所有其他预定义的格式选项,

https://angular.io/api/common/DatePipe

这个答案现在已经过时了

建议使用其他答案的DI方法代替此方法

最初的回答:

您应该能够直接使用该类

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

例如

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

如果想在组件中使用自定义管道,可以添加

@Injectable({
  providedIn: 'root'
})

注释到自定义管道。 然后,您可以将其作为一项服务使用

我使用这个方法:

 import { Component, OnInit } from '@angular/core';
    import {DatePipe} from '@angular/common';
    
    @Component({
      selector: 'my-app',
     templateUrl: './my-app.component.html',
      styleUrls: ['./my-app.component.scss']
    })
    export class MyComponent() implements OnInit {
    
      constructor(private datePipe: DatePipe) {}
    
      ngOnInit(): void {
        let date = this.transformDate('2023-02-01T06:40:49.562Z');
        console.log('date:',date);
      }
    
      transformDate(date: string) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
      }
    }