Angular2 wait till JSON file loaded

Viewed 2318

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?

2 Answers
Related