javascript - AngularJS: Performing $http request inside custom service and returning data -
i have defined custom http service in angular looks this:
angular.module('myapp') .factory('myhttpserv', function ($http) { var url = "http://my.ip.address/" var http = { async: function (webservice) { var promise = $http.get(url + webservice, { cache: true }).then(function (response) { return response.data; }); return promise; } }; return http; });
and can access service in controller so:
angular.module('myapp') .controller('myctrl', function (myhttpserv) { var webservice = 'getuser?u=3' myhttpserv.async(webservice).then(function (data) { console.log(data); }) });
however need streamline process contained inside service static url , returns data. can call in controller so:
angular.module('myapp') .controller('myctrl', function ($scope, myhttpserv) { console.log(myhttpserv.var1); console.log(myhttpserv.var2); etc... });
i can't seem tweak service functionality. know correct way it?
option 1 - use promise api
angular.module('myapp').factory('myhttpserv', function ($http) { return $http.get('http://my.ip.address/getuser?u=3', { cache: true }); });
controller:
angular.module('myapp').controller('myctrl', function ($scope, myhttpserv) { myhttpserv.then(function(response){ console.log(response.data); }); });
option 2 - using route resolve
angular.module('myapp', ['ngroute']).config(['$routeprovider', function($routeprovider) { $routeprovider. when('/myctrl', { templateurl: 'myview.html', controller: 'myctrl', resolve: { load: function (myhttpserv) { return myhttpserv; } }); }]);
service:
angular.module('myapp').factory('myhttpserv', function ($http) { var data = {}; var url = "http://my.ip.address/"; var promise = $http.get(url + 'getuser?u=3', { cache: true }).then(function (response) { data = response.data; }); return data; });
controller:
angular.module('myapp') .controller('myctrl', function ($scope, myhttpserv) { console.log(myhttpserv.data.var1); console.log(myhttpserv.data.var1); etc... });
option 3 - use $interval service
angular.module('myapp').factory('myhttpserv', function ($http) { var data = {}; var url = "http://my.ip.address/"; var promise = $http.get(url + 'getuser?u=3', { cache: true }).then(function (response) { data = response.data; }); return data; });
controller:
angular.module('myapp').controller('myctrl', function ($scope, $interval, myhttpserv) { $scope.intervalpromise = $interval(function(){ if (object.keys(myhttpserv.data).length!=0) { console.log(myhttpserv.data); $interval.cancel($scope.intervalpromise); } }, 100); });
Comments
Post a Comment