How to fix angular-translate FOUC issues while using translatePartialLoader?

a 夏天 提交于 2019-12-24 16:24:48

问题


I've been experiencing FOUC (flash of untranslated content) issues while using angular-translate. This is my setup:

.config(function ($translateProvider, defaultI18n) {
    $translateProvider
        .useSanitizeValueStrategy('sanitize')
        .translations('en-GB', defaultI18n.en)
        .useCookieStorage()
        .useLoader('$translatePartialLoader', {
            urlTemplate: '/{part}/{lang}.json'
        })
        .preferredLanguage('en-GB')
        .fallbackLanguage('en-GB');
})
.run(function ($rootScope, $translate) {
    $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
        $translate.refresh();
});

Since I'm using $translatePartialLoader in each controller view I have:

.controller('SomeController', function ($translatePartialLoader) {
    $translatePartialLoader.addPart('path-to-some-view-i18n');
})

If I remove $translate.refresh() FOUC goes away, but the text isn't updated with the new locale. Not sure if having text in my HTML files maybe causing a conflict here.

How can I remove FOUC completely but still keeping the app translating correctly?

Should I remove all text from my HTML files?

Thanks in advance.


回答1:


I changed the logic a bit and the FOUC issues seem to disappear. Instead of executing $translatePartialLoader.addPart('path-to-some-view-i18n'); in each controller, I defined for each state the respective i18n route(s) like this:

.state('state1', {
    url: '/state1',
    templateUrl: 'path-to-some-view',
    data: {
        i18n: ['path-to-some-view-i18n']
    }
})

And then, when the event $stateChangeStart is triggered:

.run(function ($rootScope, $translate, $translatePartialLoader) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if(toState.data.i18n) {
            angular.forEach(toState.data.i18n, function (value) {
                $translatePartialLoader.addPart(value);
            });
        }
    });

    $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
        $translate.refresh();
    });
});


来源:https://stackoverflow.com/questions/32123924/how-to-fix-angular-translate-fouc-issues-while-using-translatepartialloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!