1

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>

3 Answers 3

3

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
  });
}]);
Sign up to request clarification or add additional context in comments.

Comments

1

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)

6 Comments

I removed Json filter. Go error again Error: [$http:badreq]
Which means your request is failing, check stackoverflow.com/questions/39432314/…
I have corrected $htt.get() method parameter in my question. now there was no error. but my Api is returning undefined.?
Thank you for your reply. I am not sure what to check in network tab. the API which am calling is a public API for testing.
@ShakeerHussain you are getting undefined as your service method returns earlier then the response is ready. return promise and process in the controller. check my answer.
|
0
 <!DOCTYPE html>
  <html>
 <head>
 <script  src="https:/ 
/ajax.googleapis. 
 com/ajax/libs/ang 
 ularjs/1.8.2/angular. 
 min.js"></script>
 </head>
 <body>
 <a href="/restapi/getfile? 
 code=jdndndnd&attachment=true" 
 id="downloadLink">download</a>

  <script> document.  getElementById(. 
 'downloadLink'). 
 .addEventListener('click', 
 function(event) {
        event.preventDefault(); // 
  Отменить стандартное действие.    
  перехода по ссылке

        // Создать XMLHttpRequest для 
  отправки запроса
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 
 this.getAttribute('href'), true);

        // Установить заголовки
        
  xhr.setRequestHeader('Authorization', 
 'Bearer your-access-token');
        xhr.setRequestHeader('Custom- 
  Header', 'custom-value');

        xhr.responseType = 
 'arraybuffer';

        xhr.onload = function() {
            if (xhr.status === 200) {
                var blob = new 
  Blob([xhr.response], { type: 
 'application/pdf' });
                var url = 
 window.URL.createObjectURL(blob);

          // Создать ссылку для 
 скачивания файла
                var a = 
 document.createElement('a');
                a.href = url;
                a.download = 
 'downloaded-file.pdf';
                
 document.body.appendChild(a);
                a.click();

                // Очистить ссылку 
 после скачивания
                
 window.URL.revokeObjectURL(url);
            } else {
                console.error('Ошибка 
  при загрузке файла:', 
  xhr.statusText);
            }
        };

        xhr.send();
    });
  </script>
 </body>
  </html>
  **strong text**

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.