AngularJS: Executing $ http request inside user service and returning data

I defined an http user service in angular that looks like 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 I can access this service in my controller as follows:

 angular.module('myApp') .controller('myCtrl', function (myhttpserv) { var webService = 'getUser?u=3' myhttpserv.async(webService).then(function (data) { console.log(data); }) }); 

However, now I need to optimize this process so that it is contained within the service with a static URL, and it just returns the data. So that I can just call it in the controller like this:

  angular.module('myApp') .controller('myCtrl', function ($scope, myhttpserv) { console.log(myhttpserv.var1); console.log(myhttpserv.var2); etc... }); 

I cannot configure the service to receive this feature. Does anyone know the right way to do this?

+7
javascript angularjs angularjs-service
source share
1 answer

Option 1 - Use the Promises 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 Resolution

 angular.module('myApp', ['ngRoute']).config(['$routeProvider', function($routeProvider) { $routeProvider. when('/myCtrl', { templateUrl: 'myView.html', controller: 'myCtrl', resolve: { load: function (myhttpserv) { return myhttpserv; } }); }]); 

Services:

 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 the $ 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); }); 
+14
source

All Articles