Ui-route does not work

My application needs some basic data. This is why I created the service, and I use it as a model for this shared data so that it can be accessed by all controllers. I am trying to enable this service using the ui route redirection function, which says that if I return the promise, it will be resolved before the controller starts, but it does not work for me. here is my code

service:

var Data = function ($q, $http) {
var list = {};
var cachedData;
var resolveData;

resolveData = function () {
    return $http.get('/api/data')
        .then(function (response) {
            var deferred = $q.defer();

            deferred.resolve(list.setData(response.data));

            return deferred.promise;
        }, function (response) {
        });
};

list.getData = function () {
    if (cachedData) {
        return cachedData;
    }
    else {
        resolveData();
    }
};

list.setData = function (data) {

    cachedData = data;

    return data;
};
return list;
};

Data.$inject = ['$q', '$http'];

Route:

.state('temp', {
        url: 'temp',
        templateUrl: '/temp',
        controller: 'temp',
        resolve: {
            data: function (data) {
                return data.getData();
            }
        }
    })

Controller:

var temp = function(data, $scope){
    console.log('asad');
    $scope.showLoading = true;

    $scope.prefixes = data.something; //not working

    $scope.lists = data;
};

temp.$inject = ['data', '$scope'];
+4
source share
1 answer

Firstly, it will be easier to work with the plunger.

But it seems that the getData function does not return any promises.

I changed getData () to something like:

list.getData = function () {
var deferred = $q.defer();
if (cachedData) {
    deferred.resolve(cachedData);
} else {
    resolveData().then(deferred.resolve).catch(deferred.reject);
}

return deferred.promise;
};

btw, resolveData() :

resolveData = function () {
    var deferred = $q.defer();

    $http.get('/api/data')
        .then(function (response) {
            list.setData(response.data);
            deferred.resolve(response.data);
        });

    return deferred.promise;
};
+3

All Articles