Angular 2,使用typescript <key,value =“”>创建字典并加载json文件以将数据放入其中

时间:2016-03-01 13:09:38

标签: json dictionary angular

我需要一些帮助来创建具有结构的字典或列表。我创建了一个json文件(放在我的angular 2项目中),我需要将这些数据加载到创建的字典中。

我的Json文件看起来像(样本):

{
 "ACCOUNT_LOGIN_TEXT": "Login",
 "ACCOUNT_LOGOUT_TEXT": "Logout",
 "BOOKING_ACTIVE_HEADER_TEXT": "ACTIVE BOOKINGS",
 "BOOKING_LOADING_TEXT": "Loading bookings",
 "BOOKING_NONACTIVE_HEADER_TEXT": "NON ACTIVE BOOKINGS",    
}

它放在一个名为Locales的文件夹中,文件名是localeEN.json

ACCOUNT_LOGIN_TEXT应该是键,值应该是文本。是否有一种简单的方法来加载json文件并对其进行迭代以将值放入字典中,以便您可以进一步使用它?

创建了一个AppService,因为我需要在其余组件之前加载它。

@Injectable()
export class AppService {

    localeResource: 

    constructor() {

    }

    getLocaleResources(locale: string) {

    }

}

interface Locale {
    key: string,
    value: string
}

不确定localeResource类型应该如何?已经创建了一个界面,但我不确定它是否适合作为一种类型使用。

希望有人可以给我建议。

更新

我设法创建了一个实际工作的管道:)

export class ResourcePipe implements PipeTransform {

value: string = "";

constructor(private appService: AppService) {

}

transform(key: string) {

    this.appService.getResourceValue(key).subscribe((data: any) => {

        if (typeof data === "string") {
            this.value = data;
        }

    })

    return this.value;
}
}

管道从服务获取值。 然后我可以使用angular2中的管道,如:

{{ SOME_TEXT | resource }} and it works quite good.

1 个答案:

答案 0 :(得分:1)

您可以将资源加载到构造函数中,并将结果设置为localResource变量。您还可以利用EventEmitter通知服务用户(组件)已加载i18n数据。

以下是一个示例实现:

@Injectable()
export class AppService {
  localeResource: any;
  localResourceLoadedEvent: EventEmitter<boolean> = new EventEmitter();
  localResourceLoaded: boolean;

  constructor(private http:Http) {
    return this.http.get(`Locales/localeEn.json`)
             .map(res => res.json())
             .subscribe((data) => {
               this.localeResource.En = data;
               this.localResourceLoaded = true;
               this.localResourceLoadedEvent.emit(true);
             });
  }

  getLocaleResources(locale: string) {
    return localeResource[locale];
  }
}

请注意,此服务需要由所有应用程序共享,并且应在调用引导函数时定义:

bootstrap(AppComponent, [ AppService ]);

在您的组件中,您可以拥有:

@Component({
  template: `
    <div *ngIf="resourceLoaded">
      (...)
    </div>
  `
})
export class MyComponent {
  constructor(private appService:AppService) {
    this.resourceLoaded = appService.localResourceLoaded;
    if (!this.resourceLoaded) {
      this.appService.localResourceLoadedEvent.subscribe((resourceLoaded) => {
        this.resourceLoaded = resourceLoaded;
        this.resource = this.appService.getLocaleResources('En');           
      });
    } else {
      this.resource = this.appService.getLocaleResources('En');           
    }
  }
}