How to call $http.get() in Service using AngularJS
I want to inject Service in a controller. The Service will return $http.get() method.
Error : [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=JsonFilterProvider%20%3C-%20JsonFilter
Please suggest whats wrong in my code?
 <script>
        var app = angular.module("myApp", []);
        app.controller("myCntlr", ['$scope', 'myhttpService', function ($scope,  myhttpService) {
                $scope.myHttpMessage = myhttpService.httpGetService();
            }]);
 app.service("myhttpService", ['$http', '$scope', function ($http, $scope) {
            this.httpGetService = function () {
                console.log("httGetService");
               $http.get('https://reqres.in/api/users').then(function (successResponse) {
                    console.log("http Get");
                    return successResponse;
                }, function (errorResponse) {
                    console.log("http Get Error");
                    return errorResponse
                });
            };
    }]);
</script>
 <div ng-app="myApp" ng-controller="myCntlr">
        <p>Http Message:{{myHttpMessage|Json}}</p>
</div>
The actual issue is you are not getting the response from your service. So the json filter throws an error
 <p>Http Message:{{myHttpMessage | json}}</p>
Make sure yo return the result back from the service with a return command.
return  $http.get('https://reqres.in/api/users').then(function (successResponse)
 You can not inject $scope in service.  that's not allowed.  Instead, you can return promise from service and process inside controller something like this.  
app.service("myhttpService",['$http', function ($http) {
    this.httpGetService = function () {
       return $http.get('https://reqres.in/api/users');
    }
}]);
app.controller("myCntlr", ['$scope', 'myhttpService', function ($scope,  myhttpService) {
  myhttpService.httpGetService().then(function(response){
     $scope.myHttpMessage = response.data;
  }, function(error){
     //do something on failure
  });
}]);
                        链接地址: http://www.djcxy.com/p/77672.html
                        
                        
                    