【问题标题】:angular i18next::backendConnector loaded correctly, but translations not available in controller角度 i18next::backendConnector 加载正确,但控制器中没有翻译
【发布时间】:2018-08-11 16:37:31
【问题描述】:

我初始化 i18next:

if (window.i18next) {
window.i18next.use(window.i18nextXHRBackend) ;
window.i18next.use(window.i18nextSprintfPostProcessor);
window.i18next.init({
        debug: true,
        fallbackLng: 'en',
        lng: 'en',
        resGetPath: '/locales/{{lng}}/camps.json',
        backend: {
            loadPath: '/locales/{{lng}}/camps.json'
        },
    }, function (err, t) {
        return i18next ;
        console.log('resources loaded',t);
        var translate = i18next.t("nav");
        console.log("translate variable = " + translate);
    });
};

app = angular.module("ngCamps", ['ngSanitize', 'jm.i18next' , 'ngAnimate', 'ui.select']) ;

然后在我的控制器中:

app.controller("myController", ($scope, $http, $filter, $q, $i18next ) =>     {
    const resources = i18next.getResourceBundle('en','camps') ;
    console.log("resources",resources) ;
    $scope.hello = i18next.t("nav");
    console.log($scope.hello) ;

..... 页面加载时翻译 json 不可用。 但是在页面加载后,我得到一个控制台,告诉我资源已加载

控制台如下所示:

i18next::translator: missingKey undefined translation nav nav

...然后 i18next::backendConnector: 为语言加载命名空间翻译

如果我进入控制台 - 我会得到正确的翻译:

i18next.t('nav');
"My Camp"

所以看起来页面在控制器中可用翻译之前加载。

我该如何改变呢? 感谢您的帮助。

【问题讨论】:

  • 加载翻译,就像每个 xhr 请求都是异步的 -> 在引导之前调用了断言回调 -> 你可以查看 github.com/i18next/ng-i18next 它是如何解决的

标签: angularjs i18next


【解决方案1】:

i18nextLanguageChange 事件触发时,您可以使用$i18next.t,如下所示:

app.controller('myController', ($rootScope, $scope, $http, $filter, $q, $i18next) => {

  $scope.hello = '';

  $rootScope.$on('i18nextLanguageChange', function () {
    $scope.hello = $i18next.t('nav');
    console.log($scope.hello);
  });

示例:https://github.com/i18next/ng-i18next/blob/master/examples/provider/provider1.js

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2021-09-24
    • 1970-01-01
    • 2014-08-24
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多