Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 wait till JSON file loaded

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",
    ...
}

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

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

like image 483
Daniel Avatar asked Oct 19 '22 13:10

Daniel


1 Answers

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

The pipe can subscribe on this observable to update transparently the value of the message in the same way the async does:

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

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

like image 163
Thierry Templier Avatar answered Nov 15 '22 04:11

Thierry Templier