Ivan Zyranau
Ivan Zyranau

Reputation: 941

How to provide LOCALE_ID from an observable in Angular 2?

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?

Upvotes: 1

Views: 2584

Answers (2)

Milan Hlin&#225;k
Milan Hlin&#225;k

Reputation: 4430

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.

Upvotes: 1

Leon Radley
Leon Radley

Reputation: 7672

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

Upvotes: 0

Related Questions