簡體   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