Angular - Use pipes in services and components

前端 未结 8 1616
南笙
南笙 2020-11-22 09:42

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

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


        
8条回答
  •  日久生厌
    2020-11-22 10:22

    Other answers don't work in angular 5?

    I got an error because DatePipe is not a provider, so it cannot be injected. One solution is to put it as a provider in your app module but my preferred solution was to instantiate it.

    Instantiate it where needed:

    I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174

    I wanted to use it within a pipe, so my example is within another pipe:

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

    The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly.

    Make DatePipe a provider

    In your app module you could also add DatePipe to your providers array like this:

    import { DatePipe } from '@angular/common';
    
    @NgModule({
        providers: [
            DatePipe
        ]
    })
    

    Now you can just have it injected in your constructor where needed (like in cexbrayat's answer).

    Summary:

    Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself.

提交回复
热议问题