Angular使用$ translateProvider.useStaticFilesLoader翻译异步计时问题 [英] Angular Translate async timing issue with $translateProvider.useStaticFilesLoader

查看:544
本文介绍了Angular使用$ translateProvider.useStaticFilesLoader翻译异步计时问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用出色的Angular Translate($translate)指令/服务来处理多种语言环境的语言,由于我有多个语言环境文件,因此我使用便捷的$translateProvider.useStaticFilesLoader通过localeAbbr.json结构加载我的翻译文件,例如en.jsones.json等...我构建了一个Plunker来显示我的开源项目,并且该项目通过Git原始文件使用语言环境(指向实际的Github存储库,这意味着不是本地人在plunker演示中).我的项目是作为指令和服务"构建的,我做了一个小型Plunker来显示JSON文件加载的计时问题.

I am using the excellent Angular Translate ($translate) directive/service to deal with multiple Locale Languages and since I have multiple locale files I use the convenient $translateProvider.useStaticFilesLoader to load my translation files through a structure of localeAbbr.json, for example en.json, es.json, etc... I built a Plunker to show my open source project and that project uses the locale through Git raw files (pointing to the actual Github repository, meaning not local to the plunker demo). My project is built as a Directive and a Service, I made a small Plunker to show my timing issue with the JSON file loading.

所有这些说明似乎使$translateProvider.useStaticFilesLoader起作用asynchronous,而我真的需要将它设为synchronous,因为到了放声小子运行时,我已经调用了在我的消息上.

All that to say that it seems $translateProvider.useStaticFilesLoader works asynchronous while I would really need it to be synchronous because by the time the plunker runs, the JSON files are not yet parsed while I already called a $translate.instant() on my messages.

我有一个柱塞来显示问题.

这是我的快速服务演示的一部分:

And here is part of my quick Service demo:

app.factory('validationService', ['$filter', '$translate', function ($filter, $translate) {
  var service = this;
  var validationSummary = [];
  var errorMessages = [
    'INVALID_ALPHA',
    'INVALID_ALPHA_SPACE',
    'INVALID_ALPHA_NUM',
    'INVALID_BOOLEAN'
  ];

  //var $translate = $filter('translate');

  for(var i=0, ln=errorMessages.length; i < ln; i++) {
    validationSummary.push({  
      field: i,
      message: $translate.instant(errorMessages[i])
    });
  }

  // attach public functions
  service.getValidationSummary = getValidationSummary;
  return service;

  // function declaration
  function getValidationSummary() {
    return validationSummary;
  }
}]);

$ translateProvider配置

The $translateProvider configuration

app.config(['$translateProvider', function ($translateProvider) {
  $translateProvider.useStaticFilesLoader({
    prefix: 'https://rawgit.com/ghiscoding/angular-validation/master/locales/validation/',
    suffix: '.json'
    });

    // load English ('en') table on startup
    $translateProvider.preferredLanguage('en').fallbackLanguage('en');
}]);

通过控制器致电我的服务:

Call my Service through the Controller:

app.controller("TestController", function($scope, validationService) {
  var vm = this;
  vm.displayValidationSummary = true;

  vm.validationSummary = validationService.getValidationSummary();
});

最后是使用控制器的HTML:

and finally the HTML using the controller:

<div class="alert alert-danger alert-dismissable" ng-show="vm.displayValidationSummary">
  <button type="button" class="close" data-dismiss="alert" aria-hidden="true" ng-click="displayValidationSummary = false">&times;</button>
  <h4><strong>{{ 'ERRORS' | translate }}!</strong></h4>
  <ul>
      <li ng-repeat="item in vm.validationSummary">{{item.field }}: {{item.message}}</li>
  </ul>
</div>

由于我使用的是AngularJS 1.3+,因此我还发现$translate只翻译了一次,因此作者建议使用translateFilter.$stateful = true;,但我尝试了一下,但这似乎无济于事.

Since I'm using AngularJS 1.3+, I also found that $translate only gets translated once, so the author suggest to use translateFilter.$stateful = true; and I tried but that doesn't seem to help.

同样是柱塞

我已经花了数周的时间试图找到所有解决方案并对其进行编码,但是我一直没有使它起作用,我为看到我的原始翻译代码感到非常遗憾:(

I have been spending weeks on trying to find and code all kind of solution but I never got it to work and I'm really sad of seeing my raw translation code :(

请帮助!!!

编辑
我意识到我的问题并未涵盖与我的问题相关的所有内容.除了翻译延迟问题之外,我还必须传递额外的参数,这是将它们传递给翻译匿名函数的巨大问题.到诺言完成时,我的论点状态已经改变.例如:

EDIT
I realized that my question was not covering everything related to my problem. On top of the translation delay problem, I also have to pass extra arguments and that is a huge problem passing them to the translation anonymous function. By the time the promise is finished, the state of my arguments have already changed. For example:

$translate(validator.message).then(function(translation) {
    // only log the invalid message in the $validationSummary
    addToValidationSummary(formElmObj, translation);

    // error Display
    if(!isValid) {
      updateErrorMsg(translation, isValid);
    }else if(!!formElmObj && formElmObj.isValid) {
      addToValidationSummary(formElmObj, '');
    }
}, function(data) {
    throw 'Failed to translate' + data;
});

推荐答案

我找到了将额外的参数传递给promise的匿名函数的问题的答案,那就是使用

I found out the answer to my problem of passing extra arguments to the anonymous function of the promise is to use Closures, in this way the variables are the same before the promise and inside it too. So I basically have to wrap my $translate call into the closure, something like the following:

(function(formElmObj, isValid, validator) {
    $translate(validator.message).then(function(translation) {
        message = message.trim();

        // only log the invalid message in the $validationSummary
        addToValidationSummary(formElmObj, message);

        // error Display
        if(!isValid) {
          updateErrorMsg(message, isValid);
        }else if(!!formElmObj && formElmObj.isValid) {
          addToValidationSummary(formElmObj, '');
        }
    }, function(data) {
        throw 'Failed to translate' + data;
    });
})(formElmObj, isValid, validator);

现在最后,我的变量是正确的,并保持该时间点的值:)

and now finally, my variables are correct and keep the value at that point in time :)

这篇关于Angular使用$ translateProvider.useStaticFilesLoader翻译异步计时问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆