Angular - Use pipes in services and components

前端 未结 8 1553
南笙
南笙 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:27

    As usual in Angular, you can rely on dependency injection:

    import { DatePipe } from '@angular/common';
    
    class MyService {
    
      constructor(private datePipe: DatePipe) {}
    
      transformDate(date) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
      }
    }
    

    Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

    providers: [DatePipe,...]
    

    Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

    import { formatDate } from '@angular/common';
    
    class MyService {
    
      constructor(@Inject(LOCALE_ID) private locale: string) {}
    
      transformDate(date) {
        return formatDate(date, 'yyyy-MM-dd', this.locale);
      }
    }
    

    Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

    If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

提交回复
热议问题