繁体   English   中英

Angular - 在服务和组件中使用管道

[英]Angular - Use pipes in services and components

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

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

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

和 Angular 一样,你可以依赖依赖注入:

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

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

DatePipe添加到模块中的提供者列表中; 如果你忘记这样做,你会得到一个错误, no provider for DatePipe

providers: [DatePipe,...]

更新 Angular 6 :Angular 6 现在提供了管道公开使用的几乎所有格式化函数。 例如,您现在可以直接使用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);
  }
}

在 Angular 5 之前:请注意, DatePipe在版本 5 之前一直依赖于 Intl API,并非所有浏览器都支持该 API(检查兼容性表)。

如果您使用的是较旧的 Angular 版本,您应该将Intl polyfill 添加到您的项目中以避免出现任何问题。 有关更详细的答案,请参阅此相关问题

这个答案现在已经过时了

建议使用其他答案中的 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');

是的,可以通过使用简单的自定义管道来实现。 使用自定义管道的好处是如果我们以后需要更新日期格式,我们可以去更新单个文件。

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

您始终可以在任何地方使用此管道、组件、服务等

例如:

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

不要忘记导入依赖项。

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

其他答案在角度 5 中不起作用?

我收到错误,因为 DatePipe 不是提供程序,因此无法注入。 一种解决方案是将其作为应用程序模块中的提供者,但我的首选解决方案是实例化它。

在需要的地方实例化它:

我查看了 DatePipe 的源代码以了解它是如何获得语言环境的: https : //github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174

我想在一个管道中使用它,所以我的例子在另一个管道中:

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

这里的关键是从 angular 的核心导入 Inject 和 LOCALE_ID,然后注入它,以便您可以将其提供给 DatePipe 以正确实例化它。

使 DatePipe 成为提供者

在您的应用程序模块中,您还可以将 DatePipe 添加到您的 providers 数组中,如下所示:

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

    @NgModule({
        providers: [
            DatePipe
        ]
    })

现在你可以在需要的地方将它注入你的构造函数中(就像在 cexbrayat 的回答中一样)。

概括:

两种解决方案都有效,我不知道哪个 angular 会认为最“正确”,但我选择手动实例化它,因为 angular 没有提供 datepipe 作为提供者本身。

如果您不想执行new myPipe()因为您正在向管道注入依赖项,您可以注入像 provider 这样的组件并在没有 new 的情况下使用。

例子:

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

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

@Injectable({
  providedIn: 'root'
})

自定义管道的注释。 然后,您可以将其用作服务

从 Angular 6 开始,您可以从@angular/common实用程序导入formatDate以在组件内部使用。

它是在https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae引入的

我可以用作:

import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');

虽然必须提供语言环境

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

    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

我用这个方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM