sourcetip

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

fileupload 2023. 5. 28. 21:00
반응형

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

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는 이제 파이프에서 공개적으로 사용되는 거의 모든 형식 지정 기능을 제공합니다.예를 들어, 이제 기능을 직접 사용할 수 있습니다.

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) {
    const datePipe = new DatePipe("en-US");
    value = datePipe.transform(value, 'MMM-dd-yyyy');

    return value;
  }
}
{{currentDate | dateFormatPipe }}

이 파이프는 구성 요소, 서비스 등 어디에서나 항상 사용할 수 있습니다.

예:

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

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

다른 답은 각도 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 및 LOCAL_ID를 가져온 다음 이를 DatePipe에 제공하여 적절하게 인스턴스화하는 것입니다.

DatePipe를 제공자로 지정

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

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

    @NgModule({
        providers: [
            DatePipe
        ]
    })

이제 필요한 곳에 (섹브레이야트의 대답처럼) 생성자에게 주입할 수 있습니다.

요약:.

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

하기 싫다면,new myPipe()파이프에 종속성을 주입하기 때문에 공급자와 같은 구성 요소에 주입하여 새 것 없이 사용할 수 있습니다.

예:

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 기준으로 가져올 수 있습니다.formatDate부터@angular/common구성 요소 내부에서 사용할 유틸리티입니다.

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

다음과 같이 각도에서 제공하는 미리 정의된 형식 옵션을 사용할 수도 있습니다.

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

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

반응형