Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Need help chaining promises in angular

I am writing localization service which will get localization files from server, if request fails I'll request the default language. But there is a problem, I try to initialize resource in routes resolve, but I don't know how to chain my requests correctly

function Localization($http, $rootScope, $window, $filter) {
    var Localization = {
        // use the $window service to get the language of the user's browser
        language: $window.navigator.userLanguage || $window.navigator.language,
        // array to hold the localized resource string entries
        dictionary: [],
        // flag to indicate if the service has loaded the resource file
        resourceFileLoaded: false,
        // Language that is always present on server
        defaultLanguage: 'en',


        initialiseResources: function () {
            var url = '/static/js/localization/resources/' + this.language + '.json';
            return this.resourceFileLoaded || $http.get(url, {cache: false}).then(successCallback, errorCallback).then(successCallback, defaultLoadFailed)
        },

    };
    return Localization;

    function errorCallback() {
        // the request failed set the url to the default resource file
        var url = '/static/js/localization/resources/' + Localization.defaultLanguage + '.json';
        // request the default resource file
        return $http.get( url, {cache: false});
    }

    function successCallback(response) {
        // store the returned array in the dictionary
        Localization.dictionary = response.data;
        // set the flag that the resource are loaded
        Localization.resourceFileLoaded = true;
        // broadcast that the file has been loaded
        $rootScope.$broadcast('localizeResourcesUpdates');
        return response.data;
    }

    function defaultLoadFailed() {
        console.log('Localization service failed');
        $rootScope.$broadcast('LocalizationInitFailed');
    }
}

Localization.$inject = ['$http', '$rootScope', '$window', '$filter'];
angular.module('app.localization.services').factory('Localization', Localization);

Comments