javascript - Is it possible to pass GET response data back to same factory? -
question:
from controller, how can call getpages function, return data controller , replace empty page.details.refobject get response data?
is possible happen within factory regardless of controller calls function?
app.factory('pages', function($http, env){ var pages = {}; pages.details = { pages: { length: 0, offsets: [] }, ref: { //data goes here on success }, getpages: function($scope) { return $http.get(env.apiendpoint + '/' + $scope.storeslug + '/pages.json?code=' + $scope.promocode) .success(function(data){ // want pages.details.ref replaced on success of getpages pages.details.ref = data; $scope.handlepagessuccess(data); return data; }) .error(function(data, status){ // console.log('error:' + status); }); } } return pages; }); controllers: this controller calls init request
app.controller('randomctrl', function($scope, pages){ var handlesuccess = function (data) { $scope.data = data; } pages.details.getpages($scope).success(handlesuccess); }) controller #2: this controller consumes temp version of request no relationship between randomctrl. e.g controller typically directive level controller theres no bubbling between parent ctrl
app.controller('otherctrl', function($scope, pages){ $scope.temppage = pages.details.ref; }) it shouldnt matter getpages called from. want ref replaced everytime getpages called.
it seems trying manage state inside factory, not idea. not idea pass around $scope in factories. should limited own controller. instead cache promise previous call made , based on flag either return cached promise or make actual service call.
app.factory('pages', function($http, env, $q){ var pages = {}; var cachedpromise = {}; pages.details = { pages: { length: 0, offsets: [] }, getpages: function(request) { //get request key make sure returning right promise incase multiple product calls made @ same time. var reqkey = request.storeslug + request.promocode; //if call has been made , there promise return if(cachedpromise[reqkey]) return cachedpromise[reqkey]; //store promise in cache lastcall retrieval return cachedpromise[reqkey] = $http.get(env.apiendpoint + '/' + request.storeslug + '/pages.json?code=' + request.promocode) .then(function(result){ return result.data; //you can alter data , send }, function(data, status){ return $q.reject('some error'); //or return data }).finally(function(){ //remove cache map, once promise resolved. delete cachedpromise[reqkey]; }); } } return pages; }); in first controller do:-
app.controller('randomctrl', function($scope, pages){ //build request. pages.details.getpages(request).then(function (data) { $scope.data = data; }); }); in second controller same:-
app.controller('otherctrl', function($scope, pages){ //pass flag cached data. pages.details.getpages(request).then(function (data) { $scope.temppage = data; }); });
Comments
Post a Comment