Search code examples
jsonangularjsservice

AngularJS - Using a service to get JSON from server


I'm trying to learn AngularJS and need some help. I'm using version 1.4.9 and I'm trying to create a service that will get JSON from a server but I'm getting the following error: "serviceName is not defined"

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

Here is my service:

    app.service('serviceName', function ($http, $q) {
        var url= "myURL";
            function getData() {
                return $http.get(url);
            }
            return {
                getData: getData,
            }
        }
    );

Here is my controller:

    app.controller("myController", function ($scope, $http) {
        serviceName.getData().then(function (response) {
            $scope.myField = response.data;
        });
    });

Solution

  • You need to inject your service into the controller, like this:

        app.controller("myController", function ($scope, serviceName) {
            serviceName.getData().then(function (response) {
                $scope.myField = response.data;
            });
        });
    

    And you do not need $http, because that's used in the service ;)