Saturday, August 2, 2014

AngularJS: $http service call being moved to factory as well as $q promise

The Service
xxxApp.factory('myService', function(($q, $timeout, $http){
    return {

        //$http post
        method1: function() {
            return $http.post('/services', { 
                type : 'getSource',
                ID    : 'TP001'
            });
        },

        //$q promise
        method2: function() {
           var deferred = $q.defer();
      
           $timeout(function() {
             deferred.resolve('This is result 2!');
           }, 2000);
      
            return deferred.promise;
        },

        //$http get
        method3: function() {
           return $http.get('stuff');
        },

       //$http returns a promise, which has a then function, which also returns a promise
       async: function() {    
           var promise = $http.get('test.json').then(function(response) {
            // The then function here is an opportunity to modify the response
            console.log(response);
            //The return value gets picked up by the then in the controller.
            return response.data;
           });
        // Return the promise to the controller
        return promise;
        }
    };
});




The Controller

xxxApp.controller('myCtrl',function($scope, myService){
    $scope.result1 = [];

    var handleSuccess = function(data, status) {
        $scope.result1 = data;
        console.log($scope.result1);
    };

    myService.method1().success(handleSuccess);

    $scope.result2 = myService.method2();
    $scope.result3 = myService.method3();


    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
    $scope.data = d;
    });

});


And the view part:

<html ng-app="myApp" ng-controller="myCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2/angular.min.js"></script>
<meta charset=utf-8 />
<title>Factory $q promise etc.</title>
</head>
<body>
  <div ng-show="!result1">Waiting...</div>
  <div>{{result1}}</div>
  <hr>
  <div ng-show="!result2">Waiting...</div>
  <div>{{result2}}</div>
  <hr>
  <div ng-show="!result3">Waiting...</div>
  <div>{{result3}}</div>
</body>
</html>

No comments:

Post a Comment