Search code examples
htmlangularjscallbackangular-servicesangular-controller

Unknown provider: callbackProvider <- callback


I am stuck with this code for very long time and apply all the patches available on net but didn't find the effective one.It is still giving error while calling service from controller. Here the code below

<HTML ng-app="myApp">
<body ng-controller = "myCtrl">
    <div>{{me}}</div>
</body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
    <script>

         var app = angular.module('myApp',[])

        app.controller('myCtrl',function($scope,myService){
            myService.getx(function(data){
            console.log(data);
            $scope.me = "data"; 
            });

        });

        </script>
        <script>
        app.service('myService',function($http,callback){
        this.getx= function(){
                 return $http({
                method: "GET",

                url: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
              }).then(function (response) {
                      console.log(response)
                     return callback(response);
                 }, function (error) {
                     throw error;
                     console.log("Error",error)
                 });

        }

        });

    </script>
</HTML>

Solution

  • i'd rewrite it like this:

    APP CTRL:

     var app = angular.module('myApp',[])
    
     app.controller('myCtrl',function($scope,myService){
       myService.getx()
         .then(
         function(data){ //handle the $http promise here
           console.log(data);
           $scope.me = "data"; 
         },
         function(err){
           console.log('error:' + err);
         });
    
     });
    

    SERVICE:

    app.service('myService',function($http){
      return {
        getx: function() {  
         return $http({  //the $http returns a promise
           method: "GET",
           url:"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
           });
        }
      }
    });