angularjsangular-translateangular-cookies

How to use $cookies to cache bust Angular Translate static files


The core issue here is that I can't inject $cookies into a config block, and configuring static file loading in Angular Translate seems to only be able to be done in a config block. I have a cookie containing my app version that I'd like to use as a query parameter for my static translation files to have a form of cache busting in between releases.

Here's the code:

(function( ) {
    'use strict';

    angular.module( 'vcp.core' ).
        config( configureTranslationResources );

    function configureTranslationResources( $translateProvider ) {

        var $cookies;
        angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) {
            $cookies = _$cookies_;
        }]);

        var vcpVersion = $cookies ? $cookies.get('vcp-version') : '';

        $translateProvider.useStaticFilesLoader({
            prefix: '/v2/assets/i18n/',
            suffix: '.json?v=' + vcpVersion
        });

    }

})( );

This feels odd and like there should be a better way. I can't intuit from the Angular Translate docs how to configure static file loading in a run block (not that that feels much better than this approach), and there doesn't appear to be a way to get at a cookie within a config block through $cookiesProvider.

Perhaps this approach altogether is a bad idea and there's a better way to solve the problem?


Solution

  • If your page is dynamically generated, you could put the version number in the HTML instead of a cookie. For example, in index.html in a one-page app:

    <script>
    'use strict';
    angular.module('vcp.settings', [])
    .constant('vcpVersion', '{{vcp_version}}');
    </script>
    

    Where vcp_version is injected server-side. Since it's static for the duration of a deployment, your server can cache the generated HTML.

    Constants are available during configuration, so you can inject the version number into your config function like this:

    angular.module( 'vcp.core', ['vcp.settings'] ).
        config( configureTranslationResources );
    
    function configureTranslationResources( $translateProvider, vcpVersion ) {
        ...