This repository has been archived by the owner on Apr 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 184
Example: Fetching Translations Live
Dan Patz edited this page Mar 6, 2018
·
4 revisions
In this example, we create a TranslationsFetcherService
and use it to load the translations at runtime. It uses ic-ajax to do the AJAX lookup in an Ember-safe manner. It assumes you have an API endpoint, GET /my/api/translations.json
, whose response looks like
{
"en": { "welcome.message": "Hello" },
"es": { "welcome.message": "Hola" }
}
// app/services/translations-fetcher.js
import Ember from "ember";
import { request } from "ic-ajax";
const { Service, inject } = Ember;
const PATH = '/my/api/translations.json';
export default Service.extend({
i18n: inject.service(),
fetch() {
return request(PATH).then(this._addTranslations.bind(this));
},
_addTranslations(json) {
const i18n = this.get('i18n');
Object.keys(json).forEach((locale) => {
i18n.addTranslations(locale, json[locale]);
});
}
});
Then we use the beforeModel
hook in ApplicationRoute
to load the translations before anything else happens in the route:
// app/application/route.js
// app/services/translations-fetcher.js
import Ember from "ember";
const { Route, inject } = Ember;
export default Route.extend({
translationsFetcher: inject.service(),
beforeModel: function() {
return this.get('translationsFetcher').fetch();
}
});