简体   繁体   中英

AngularJS: $http get Json from external file

I am a newbie at angular and not too strong in javascript to begin with. I'm trying to make an app using ionic framework. And im trying to get a list from a json file. I've successfully made it work with the raw json in a variable. But i'm now trying to use $http.get() to retrieve it from a remote file in my project folder.

.service('staffServices', ['$q', '$http', staffService]);

function staffService($q, $http) {
  var staffs = {};
  var promise = $http.get("/js/jsons/settings.json")
  .success(function(response) {
    staffs = response.staffSettings;
    console.log(staffs);    //HAS WHAT I NEED
  });
  console.log(staffs);      //EMPTY OBJECT


  return {
    loadAllSettings: function () {          
      return $q.when(staffs);          
    },
    query: function (params) {
      return filterFilter(staffs, params);
    },
    get: function (params) {
      return this.query(params)[0];
    }
  }
};

For some reason i can't access the result outside of the .success() function. I'm not sure if this is due to my ignorance in javascript or my newbie status in angular. Please help me out

This is my controller below. self.settings never gets populated and always returns an empty object

.controller("staffCtrl", function (staffServices) {
  var self = this;

  self.settings = [];
  staffServices.loadAllSettings()
  .then(function (settings) {
    self.settings = [].concat(settings);
    console.log(settings);
  });
});

I believe the problem is how you're handling the $q and the promise, you could try this also:

// Removed irrelevant return functions temporarily
.service('staffServices', ['$q', '$http', staffService]);

function staffService($q, $http) {
    var deferredPromise = $q.defer();
    var staffs = {};
    var promise = $http.get("/js/jsons/settings.json")
    .success(function(response) {
        staffs = response.staffSettings;
        console.log(staffs);
        deferredPromise.resolve(staffs);
    })
    .error(function(){
        deferredPromise.reject();
        console.log('Unsucessful json call');
    });

    return {
        loadAllSettings: function () {
            return deferredPromise.promise;
        }
    }
};

.controller("staffCtrl", function (staffServices) {
    var self = this;
    self.settings = [];
    staffServices.loadAllSettings()
    .then(function (settings) {
        console.log(settings);
        self.settings = [].concat(settings);
    });
});

The $http.get call is asynchronous, so when you call console.log inside of the .success callback, that statment doesn't actually "happen" until the $http.get request has resolved.

The second time you call console.log, outside of the .success statement, the get request has not resolved yet, so staffs is still the same empty variable it was at the beginning.

If this answer doesn't make sense to you, or you are not familiar with asynchronous stuff, might I recommend you check out this question which does a good job of explaining asynchronous calls.

As for the JSON not returning properly, I believe that $q.when (from the loadAllSettings() function) should be returning a promise, when at present it is returning the JSON object staffSettings. To use a .then call on the returned statement, it needs to be a promise. Try setting staffs to just be equal to response, and then retrieving the .staffSettings attribute in the controller.

.controller("staffCtrl", function (staffService) {
  var self = this;

  self.settings = [];
  staffService.loadAllSettings()
  .then(function (settings) {
    self.settings = [].concat(settings.staffSettings);
    console.log(settings);
  });
});

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