Programing

각도-서비스 및 구성 요소에 파이프 사용

lottogame 2020. 3. 17. 08:32
반응형

각도-서비스 및 구성 요소에 파이프 사용


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에 의존하고 있음을 경고 합니다 ( 호환성 테이블 확인 ).

이전 Angular 버전을 사용하는 경우 Intl문제를 피하기 위해 프로젝트에 폴리 필을 추가해야합니다 . 자세한 답변 은이 관련 질문참조하십시오 .


이 답변은 이제 구식입니다

이 접근법 대신 다른 답변의 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')
    }
}

여기서 핵심은 각도의 코어에서 Inject 및 LOCALE_ID를 가져온 다음 DatePipe에 제공하여 올바르게 인스턴스화하는 것입니다.

DatePipe를 공급자로 설정

앱 모듈에서 다음과 같이 제공자 배열에 DatePipe를 추가 할 수도 있습니다.

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

@NgModule({
    providers: [
        DatePipe
    ]
})

이제 cexbrayat의 답변과 같이 필요할 때 생성자에 주입 할 수 있습니다.

요약:

어느 솔루션이든 효과가 있었지만 어느 각도가 가장 "올바르다"고 생각할지 모르겠지만, 각도는 공급자로서 날짜 파이프를 제공하지 않았기 때문에 수동으로 인스턴스화하기로 결정했습니다.


파이프에 종속성을 주입하기 때문에 'new myPipe ()'를 원하지 않으면 공급자와 같은 구성 요소를 주입하고 새로운없이 사용할 수 있습니다.

예:

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

Angular 6 formatDate부터는 @angular/common유틸리티 에서 가져와 컴포넌트 내부에서 사용할 수 있습니다 .

그것은에서 intruduced했다 https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae

나는 다음과 같이 사용할 수 있습니다 :

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

로케일을 제공해야하지만


컴포넌트에서 사용자 정의 파이프를 사용하려는 경우 추가 할 수 있습니다.

@Injectable({
  providedIn: 'root'
})

사용자 정의 파이프에 주석. 그런 다음 서비스로 사용할 수 있습니다


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

참고 URL : https://stackoverflow.com/questions/35144821/angular-use-pipes-in-services-and-components

반응형