javascript - AngularJS: $http get Json from external file -


i newbie @ angular , not strong in javascript begin with. i'm trying make app using ionic framework. , im trying list json file. i've made work raw json in variable. i'm trying use $http.get() retrieve remote file in 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 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 reason can't access result outside of .success() function. i'm not sure if due ignorance in javascript or newbie status in angular. please me out

this controller below. self.settings never gets populated , returns 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 problem how you're handling $q , promise, try 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);     }); }); 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -