angularjs - Angular Service - Passing 'this' -
i attempting use external function reduce repeating standard $http call code within angular service , having think scope/this issues. question is, how amend service can make use of 'this' myservice in calls apiget function
example service code:
angular .module('myapp') .factory('myservice', ['$http', function($http) { function myservice() { this.uid; this.stuff; this.things; } myservice.build = function() { return new myservice(); }; myservice.prototype.setuid = function(uid) { this.uid = uid; }; // key part of problem code - have tried this: myservice.prototype.getstuff = apiget.apply(this,[$http,'stuff',this.uid]); // , this: myservice.prototype.getthings = apiget($http,'things',this.uid); }]);
example external function code:
function apiget($http,collection,uid) { return function() { return $http({ method: 'get', url: '/php/'+collection+'/'+uid, headers: { 'content-type': 'application/json' } }).then(function(response) { return response.data; }); } };
the last lines of service having trouble - if 'hardcode' uid function call service works fine, when use 'this' within arguments call function uid appears 'undefined'.
i've key bits of controller code below - instantiate service , use setuid method apply uid. after other methods within controller call myservice.getstuff methods, etc.
this.svc = new myservice(); this.svc.setuid(uid);
it works perfectly, including 'this' bit if don't use apiget function , create service method long hand, i.e:
myservice.prototype.getstuff = function() { return $http({ method: 'get', url: 'php/stuff/'+this.uid, headers: { 'content-type': 'application/json' } }).then(function(response) { return response.data; }); };
btw, i'm pretty new angular , head spinning slight respect scope, $scope, etc
angular services singletons, there's no need deal instance/prototypes directly (since 1 copy created).
angular .module('myapp') .factory('myservice', ['$http', 'baseservice', function($http, httpget) { var uid; //to set setuid; var myservice = object.create(baseservice); //'inherits' baseservice angular.extend(myservice, { //extends custom methods build: build, setuid: setuid, getstuff: _.partial(httpget, $http, "stuff"), getthings: _.partial(httpget, $http, "things"), }); return myservice; function build (){...} function setuid (){...} function getstuff (){...} function getthings (){...} }]);
to use service, inject service , you'll have access to:
myservice.getthings(this.uid); //calls httpget($http, 'things', uid); myservice.getstuff(this.uid); //calls httpget($http, 'stuff', uid);
Comments
Post a Comment