2

On my app, I need to recover data (json) by making multiples validations using http requests before all my app starts. So my problem is that I'm using angular.run() to make all the http requests and resolving all of the validations with promises.

The problem is, not all of my promises are executed before my app is started.

part of my code is:

appModule.run(configRun);

configRun.$inject = [
'$http', '$rootScope', 'gettextCatalog', 'ipLoadDataService',
'webStorageService', 'ipDataSetParserService'];

function configRun($http, $rootScope, gettextCatalog, ipLoadDataSrv, webStrSrv, dataSetParser) {
    webStrSrv.clear();

    ipLoadDataSrv.getHeadDataSet2()
        .then(function (responseHead) {

            if (ipLoadDataSrv.updatedDataSet2(responseHead.headers["last-modified"])) {

                //save into localstorage
                webStrSrv.clear();
                webStrSrv.setItem("last-modified", { date: responseHead.headers["last-modified"] });

                ipLoadDataSrv.getDataSet2()
                    .then(function (responseData) {

                        $rootScope.cabecera = responseData;
                    })
            }
        })
}

// LoadDataService
appModule.factory('ipLoadDataService', loadDataService);

loadDataService.$inject = ['$http',
    '$q',
    'webStorageService',
    'myPrjEnvironment',
    'ipDataSetParserService'];

function loadDataService($http, $q, webStoreService, myPrj, dataSetParser) {
    var eventMap = [];

    var ip_loadDataService = {
        getHeadDataSet2: getHeadDataSet2,
        requestDataSet: requestDataSet,
        updatedDataSet2: updatedDataSet2,
        getDataSet2: getDataSet2
    };

    return ip_loadDataService;

    function getHeadDataSet2() {
        /*HEAD*/
        var deferred = $q.defer();

        $http.head(myPrj.URL_DATA)
            .success(function (data, status, headers, config) {
                var response = [];
                response.data = data;
                response.headers = headers();
                deferred.resolve(response);

                //return deferred.promise;

            }).error(function (data, status) {
                deferred.reject(data);
            });
        return deferred.promise;
    }

    function getDataSet2() {
        return xhr('get', [myPrj.URL_DATA]);
    }

    function updatedDataSet2(last_date_modified) {
        //var self = this;
        var dateOnWebStore = webStoreService.getItem("last-modified");

        if (dateOnWebStore === null || Date.parse(dateOnWebStore.date) < Date.parse(last_date_modified))
            return true;

        return false;
    }

    function xhr(type, config) {
        if (!config && angular.isArray(type)) {
            config = type;
            type = 'get';
        }
        var deferred = $q.defer();
        $http[type].apply($http, config)
            .success(function (data, status, headers, config) {
                var response = [];
                response.data = data;
                response.headers = headers();
                deferred.resolve(response);
            })
            .error(function (error) {
                deferred.reject(error);
            });
        return deferred.promise;
    }
}
1

2 Answers 2

2

Answering the question in your second post, maybe you better edit your original post with the new issue you encountered.

If what you are looking for is a way to activate a state (home.myPrjMain in your case) you can do this in various ways:

  1. Using JS - use $state.go(). See - $State documentation

  2. Using directive - use the ui-sref directive with the name of the required state. See - ui-sref documentation

  3. Using regular html href (Navigate to url) - with the full address of the state you need. In your case, "/main".

I hope this was helpful

Sign up to request clarification or add additional context in comments.

Comments

0

Have the UI start in an initial loading state then use ui-router to wait for the various pieces to resolve before going to the initial state.

Here is a fiddle showing how it works. Fiddle

I did two parts, one with a single fake service call using timeout and a second with a chained set of calls,.

 this.slowServiceCall = function(input, delay) {
        var deferred = $q.defer();
        var workFinished = function () {
            deferred.resolve(input);
        };
        $timeout(workFinished, delay);
        return deferred.promise;
    };

this.slowChainedServiceCall = function(input, delay) {
        var deferred = $q.defer();        
        var workFinished = function () {
            deferred.resolve(input);
        };
        $timeout(workFinished, delay);
        var promiseChain = deferred.promise.then(function(result) {
            var deferred2 = $q.defer();
            $timeout(function(){
                deferred2.resolve(result + ' Second Piece');
            },100);
            return deferred2.promise;
        });
        return promiseChain;
    };

4 Comments

there is an alternative to don't use $timeout? why? -- because the json file that i'm trying to load into the .run() could take more or less time that i define into the $timeout. For example is i change the getDataSet2 method function getDataSet2() { var deferred = $q.defer(); $http({ method: 'POST', url: iProtectEnv.URL_DATA }).success(function(response) { deferred.resolve(response); }).error(function(response) { deferred.reject(response); }); return deferred.promise; } the .run() WORKS
'but i dont need this'
@julioVG The timesouts are to fake backend service delays. Replace the $q.defer() with your service call. The real change is to let the ui-router handle the resolving of data to your controllers. It opens up a lot more possibilities, and keeps you from duplicating state handling logic into your controllers. github.com/angular-ui/ui-router/wiki#resolve
the point is: when i launch my app, i have to receive a json file and save it into my localStorage (the boss want's that) before save it i have to see if that json file was modified, it means make a HEAD request to verify this. After that if the json was modified i have to Get ir (it means make a GET request) after, clean my LocalStorage and after that parse that json file and save into the localStorage. The point: those HEAD, GET request are promises and it doesnt resolve FAST. i want get all information and save into LS and so after all of that launch my app. can someone help me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.