Microsoft Excel Microsoft Excel - 5 months ago 15
AngularJS Question

Angular JS - Receiving information from a service

So I have a controller and service pair that are functioning properly right now, but my boss wants me to move the success/error/finally blocks from the controller to the service.

Controller Function:

$scope.createUserButton = function () {
$scope.isBusy = true;
creationService.makeNewUser($scope.form)
.success(function (data) {
var user = JSON.parse(data);
if (typeof user !== 'undefined') {
$scope.testusers.push(user);
}

}).error(function () {
notify({
message: 'Could not create user',
classes: 'alert-danger',
templateUrl: 'partials/settingNotification.html'
});
}).finally(function () {
$scope.isBusy = false;
});
};


Service:

service('creationService', ['restfulRepo', '$http',
function (restfulRepo, $http) {
this.makeNewUser = function (tempuser) {
return $http({
url: 'http://localhost:60098/***/*************/******',
data: tempuser, method: 'PUT'
});
};
}]);


The problem that I'm having is that if I move the success or finally blocks to the service, then they don't have access to the isBusy flag or to the testusers array. The array is bound to a graph in the controller that displays the information handed back.

Answer

With my response, you can let data binding alleviate that for you. Notice how we set the controller & service isBusy variables.

Controller:

$scope.isBusy = creationService.isBusy; //1-way Data Binding
$scope.createUserButton = function () {
            creationService.isBusy = true;
            creationService.makeNewUser($scope.form).then(
                    function(user){
                       $scope.testusers.push(user);
                    }, function(error){
                       notify({
                       message: error,
                       classes: 'alert-danger',
                       templateUrl: 'partials/settingNotification.html'
                       });
                    });

        };

Service:

service('creationService', ['restfulRepo', '$http', '$q', function (restfulRepo, $http, $q) {
this.isBusy = false;

this.makeNewUser = function (tempuser) {
var defer = $q.defer();
  $http({
    url: 'http://localhost:60098/***/*************/******',
    data: tempuser, method: 'PUT'
  }).success(function (data) {
                var user = JSON.parse(data);
                if (typeof user !== 'undefined') {
                    defer.resolve(user);
                }else{
                   defer.reject("Undefined user");
                }
            }).error(function () {
                defer.reject('Could not create user');
            }).finally(function () {
                this.isBusy = false;
            });
     return defer.promise;
  };
}]);