javascript - Fetch data using $http for use with a custom service -


i'm trying create custom service pulls list of defined statuses server use in forms, far have:

simpletaskapp.factory('storystatus', function($http) {     var data = null;     var promise = $http({             url: '/story-status/',             method: 'get'         }).success(function (resp) {             data = resp;         });     return {list: data }}; }); 

i understand won't work since $http asynchronous, have no desire run request more once. i'd treat static variable in effect, if ever storystatus.list called, should check whether empty , attempt populate itself.

you should work with promises instead of against them.

you don't need store data because can store promise. point of promises don't know when they'll done. don't know when data available.

so service must return promise. that's okay:

simpletaskapp.factory('storystatus', function($http) {   var promise;    function getdata() {     if ( ! angular.isdefined( promise ) ) {       promise = $http({         url: '/story-status/',         method: 'get'       });     }      return promise;   }    return { list: getdata }; }); 

in service, $http call called once, return promise whenever call simpletaskapp.list(). controller calls doesn't need know if data there yet because react same regardless, e.g.:

simpletaskapp.controller('mainctrl', function($scope, storystatus) {   storystatus.list().then(function( data ) {     $scope.statuses = data.statuses;   }); }); 

if data retrieved, then run immediately; if not, run when data gets back. controller doesn't need know internal state of storystatus service.

so promises not asynchronous tasks, keep our components decoupled, big deal in angularjs - , should in other frameworks too!


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -