【问题标题】:How to do error handling for the event $translateChangeSuccess?如何对事件 $translateChangeSuccess 进行错误处理?
【发布时间】:2017-02-02 09:06:29
【问题描述】:

我在控制器中注册了$translateChangeSuccess 事件(在实例化控制器时)。

$rootScope.$on('$translateChangeSuccess', function () {
    console.log("It entered translateChangeSuccess");
    A = $translate.instant('aaa');
    B = $translate.instant('bbb');
});

所以 98% 的事件在控制器实例化期间/之后触发。但大约 2% 的时间我坚信事件在控制器实例化(即注册事件)之前发出。所以使用 $translateChangeSuccess 事件是不可靠的。

我可以做些什么来避免这种情况?我怎样才能让事件每次都触发而不失败?

【问题讨论】:

  • 你要去$translateChangeSuccess那里做什么?
  • @JaganathanBantheswaran 嗨,我已经更新了代码。我在里面做翻译。

标签: angularjs localization internationalization angular-translate


【解决方案1】:

您无法避免上述情况。因为无论您的控制器是否启动,只要翻译文化(区域设置)发生变化,$translateChangeSuccess 就会被触发。

$translateChangeSuccess 将开始执行已为此事件注册的侦听器,并且不会等到您的控制器启动并注册您的侦听器。

而且,如果 $translateChangeSuccess 在您的控制器启动之前已经触发,则意味着文化/区域设置没有变化。因此您的翻译语句将生成应用最新文化/语言环境的输出。

所以在你的控制器的构造函数或初始化函数中,你可以有这样的东西,

function init() {

   translate(); // execute this because $translateChangeSuccess might have fired already.

   $rootScope.$on('$translateChangeSuccess', function () {
       console.log("It entered translateChangeSuccess");
       translate();
   });

}

function translate() { 
    A = $translate.instant('aaa');
    B = $translate.instant('bbb');
}

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 1970-01-01
    • 2019-08-02
    • 2013-12-02
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多