简体   繁体   中英

Asynchronously function returns undefined with $q deferred

I am calling my data from my api through a factory that looks like this:

app.factory('Service', ['$http', function ($http) {

var urlBase = 'http://localhost:50476/api';
var Service = {};

Service.getComp = function () {
    return $http.get(urlBase + '/complaints')

};

return Service;
}]);

Then I use my controller to use the directive:

getComp();
$scope.comp = [];

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

    Service.getComp()
    .success(function (comp) {
        console.log('comp', comp); //returns array data
        $scope.comp = comp.data;
        deferred.resolve(comp);
    })
    .error(function (error) {
        $scope.error = 'error' + error.message;
    });

    return deferred.promise;
}

$scope.index = 0;
$scope.complaints = $scope.comp[0];
console.log($scope.complaints); //undefined
console.log($scope.comp); //array of 0

When I try to access the items outside of the function it is undefined. I tried to look for resolutions like using $q but it is still not displaying data. When I added the deferred part my ng-repeat stops working as well.

Try this:

getComp();
$scope.comp = [];

function getComp() {
    return Service.getComp()
    .success(function (comp) {
        $scope.comp = comp.data;
        $scope.complaints = $scope.comp[0];
    })
    .error(function (error) {
        $scope.error = 'error' + error.message;
    });
}

The values are undefined when you do your logs because those lines run before your request comes back from the server. That's why setting $scope.complaints has to go into the success callback.

if you want to make sure complaints are loaded on certain states before you start your logic you can use ui-routers resolve keyword (i suppose you are using ui-router with ionic - standard package)

In you main.js

$stateProvider.state('yourState', {
  resolve: {
    complaints: function(Service) {
      return Service.getComp();
    }
  }
});

in your controller you can then inject complaints

.controller('myController', function(complaints) {
   $scope.complaints = complaints;
})

resolve at $stateProvider will block and wait for the promise to resolve...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM