Angular2等到JSON文件加载

Angular2等到JSON文件加载

本文介绍了Angular2等到JSON文件加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我加载一个JSON文件,如下所示:

Currently I'm loading a JSON file as follows:

translation.service.ts

@Injectable()
export class TranslationService {

    private _messages = [];

    constructor(private _http: Http) {
        var observable = this._http.get("/app/i18n/localizable.it.strings").map((res: Response) => res.json());
        observable.subscribe(res => {
            this._messages = res;
        });
    }

    getTranslationByKey(key: string, args?: any[]) {
        return this._messages[key];
    }
}

localizable.it.strings

{
    "home.nav.calendar": "Calendar",
    ...
}

我的 TranslationService 中被注入了我的 HomeComponent 但问题是,当我尝试读取这个值通过当呈现页面加载它们仍然需要管。

My TranslationService gets injected in my HomeComponent but the problem is that when I try to read this values through a pipe they still needs to be loaded when the page is rendered.

translate.pipe.ts

@Pipe({name: 'translate'})
export class TranslatePipe implements PipeTransform {

    constructor(private _translation: TranslationService) {}

    transform(value: string, args: string[]) : any {
        return this._translation.getTranslationByKey(value);
    }
}

不知道如何任何页面被载入前从JSON文件加载的所有值?

Any idea how to load all values from a JSON file before any page gets loaded?

推荐答案

我认为你可以适应位服务和管道,使当数据准备/引擎盖下加载来处理。

I think that you could adapt a bit your service and pipe to make to handle when data are ready / loaded under the hood.

首先添加一个可观察到当数据在服务被加载到通知:

First add an observable to notify when the data are loaded in your service:

@Injectable()
export class TranslationService {

  private _messages = {};

  private translationLoaded : Observable<boolean>;
  private translationLoadedObserver : Observer<boolean>;

  constructor(private _http: Http) {
    this.translationLoaded = Observable.create((observer) => {
      this.translationLoadedObserver = observer;
    });

    var observable = this._http.get("app/i18n/localizable.it.strings").map((res: Response) => res.json());
    observable.subscribe(res => {
      this._messages = res;
      this.translationLoadedObserver.next(true);
    });
  }

  getTranslationByKey(key: string, args?: any[]) {
    return this._messages[key];
  }
}

管道可以在此观察到的订阅透明更新消息以相同的方式的值异步确实

@Pipe({
  name: 'translate',
  pure: false  // required to update the value when data are loaded
})
export class TranslatePipe implements PipeTransform {
  constructor(private _ref :ChangeDetectorRef, private _translation: TranslationService) {
    this.loaded = false;
  }

  transform(value: string, args: string[]) : any {
    this.translationLoadedSub = this._translation.translationLoaded.subscribe((data) => {
      this.value = this._translation.getTranslationByKey(value);
      this._ref.markForCheck();
      this.loaded = true;
    });

    if (this.value == null && this.loaded) {
      this.value = this._translation.getTranslationByKey(value);
    }
    return this.value;
  }

  _dispose(): void {
    if(isPresent(this.translationLoadedSub)) {
      this.translationLoadedSub.unsubscribe();
      this.translationLoadedSub = undefined;
    }
  }

  ngOnDestroy(): void {
    this._dispose();
  }
}

下面是相应的plunkr:。

Here is the corresponding plunkr: https://plnkr.co/edit/VMqCvX?p=preview.

这篇关于Angular2等到JSON文件加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:02