1

In Angular 2, in order to localize date pipe you need to provide LOCALE_ID. I have a service LocaleService that exposes locale$: Observable<string> which implements BehaviorSubject<string>. I don't want to add any state to this service, I want it to be completely reactive. How can I obtain information from this service when providing LOCALE_ID?

Ivan Zyranau
  • 879
  • 2
  • 14
  • 33

2 Answers2

1

Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn’t work, if you want to change the language during runtime. See my answer here.

Milan Hlinák
  • 4,260
  • 1
  • 30
  • 41
0

A pipe can return an Observable.

import { Pipe, PipeTransform } from '@angular/core';
import { LocaleService } from 'shared/locale.service';
import { Observable } from 'rxjs/Observable';
import { formatDate } from 'somelibrary';
import 'rxjs/add/operator/map';

@Pipe({
  name: 'myDate',
  pure: false
})
export class MyDatePipe implements PipeTransform {

  constructor(private localeService: LocaleService) { }

  transform(date: string): Observable<String> {
    return this.localeService.locale$.map(locale => formatDate(date, locale));
  }
}
Leon Radley
  • 7,596
  • 5
  • 35
  • 54
  • While this is a solution, I take it as OP wants to know how to set LOCALE_ID and keep on using standard date pipe – superjos Apr 03 '17 at 19:56