import { Inject , Injectable , Provider , Optional , SkipSelf } from '@angular/core' ; import { LOCAL_PROVIDER_TOKEN } from './locale-provider.token' ; import { BehaviorSubject , Observable } from 'rxjs' ; import zh_CN from './locale/zh_CN' ; @ Injectable ( ) export class LocaleProviderService { private _locale : any = undefined ; private _change = new BehaviorSubject < any > ( this . _locale ) ; constructor ( @ Inject ( LOCAL_PROVIDER_TOKEN ) locale ) { this . setLocale ( locale || zh_CN ) ; } get localeChange ( ) : Observable < any > { return this . _change . asObservable ( ) ; } getLocaleValue ( keyPath ) { const content = this . _getObjectPath ( this . _locale , keyPath ) as string ; if ( typeof content === 'string' ) { return content ; } return '' ; } getLocaleSubObj ( keyPath ) { const content = this . _getObjectPath ( this . _locale , keyPath ) as object ; if ( typeof content === 'object' ) { return content ; } return null ; } setLocale ( locale ) { if ( ! locale || ( this . _locale && this . _locale . locale === locale . locale ) ) { return ; } this . _locale = locale ; this . _change . next ( locale ) ; } getLocaleId ( ) { return this . _locale && this . _locale . locale ? this . _locale . locale : '' ; } getLocale ( ) { return this . _locale ; } private _getObjectPath ( obj , path ) { let res = obj ; const paths = path . split ( '.' ) ; const depth = paths . length ; let index = 0 ; while ( res && index < depth ) { res = res [ paths [ index ++ ] ] ; } return index === depth ? res : null ; } } export function LOCALE_PROVIDER_SERVICE_FACTORY ( exist , locale ) { return exist || new LocaleProviderService ( locale ) ; } export const LOCALE_PROVIDER_SERVICE_PROVIDER = { provide : LocaleProviderService , useFactory : LOCALE_PROVIDER_SERVICE_FACTORY , deps : [ [ new Optional ( ) , new SkipSelf ( ) , LocaleProviderService ] , LOCAL_PROVIDER_TOKEN ] } ;