javascript - Return a value from AngularJS API service to controller -
if have service looks this:
app.factory('user', function($http, user) { var user = function(data) { angular.extend(this, data); }; user.prototype.create = function() { var user = this; return $http.post(api, user.getproperties()).success(function(response) { user.uid = response.data.uid; }).error(function(response) { }); }; user.get = function(id) { return $http.get(url).success(function(response) { return new user(response.data); }); }; return user; });
how i, in controller, user
created in get()
function?
currently have is:
app.controller('userctrl', function($scope, user) { $scope.user = null; user.get($routeparams.rid).success(function(u) { $scope.user = new user(u.data); }); });
the issue userctrl
getting api response, not value returned success()
in factory. i'd prefer making new user in factory, opposed passing api response controller.
edit: may 5th 2015
i learnt deferred anti-pattern while trying answer question.
so can avoid using $q.defer()
, use following code achieve same result.
service
user.get = function(id) { return $http.get(url).then(function(response) { return new user(response.data); }); };
controller
user.get($routeparams.rid).then(function(u) { $scope.user = u; });
original answer below:
i think looking $q
service allows post processing on response asynchronous $http
service , return controller promise. check out documentation here https://docs.angularjs.org/api/ng/service/$q
so inject $q
service in factory , change user.get
function below.
user.get = function(id) { var deferred = $q.defer(); $http.get(url).success(function(response) { deferred.resolve(new user(response.data)); }).error(function(error) { deferred.reject(error); }); return deferred.promise; };
and in controller can do
user.get($routeparams.rid).then(function(u) { $scope.user = u; }, function(error) { //log error });
Comments
Post a Comment