2

I'm trying to pull data from a JSON API, using the $http method, however AngularJS keeps throwing an error that $http is not defined, even though it has been defined in the controller.

Controller:

app.controller("CompaniesController", ['$scope', '$http', 'companyService', function($scope, $http, companyService) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

   $scope.add = function(newCompany) {
       companyService.addCompany( {
           id: newCompany.id,
           name: newCompany.name,
           primary_contact: newCompany.primary_contact,
           address: newCompany.address,
           function: newCompany.function,
           telephone: newCompany.phone,
           fax: newCompany.fax,
           url: newCompany.url
       });
    };

    $scope.companies = companyService.getCompanies();

}]);

Service:

app.service('companyService',[function(){
    var companies = [];
    return {
        addCompany: function(company){
            companies.push(company);
        },
        getCompanies: function(){
            $http({method: 'GET', url: '/api/example/view/4553'}).success(function(data) {
                var companies = data; // response data
            });
            return companies;
        }
    }
}]);

1 Answer 1

5

You should inject $http into your 'companyService' service, like so

app.service('companyService',['$http', function($http){
    ...

By the way, you can remove it from 'CompaniesController' because you don't use it there directly.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly! Thank you so much, and for such a quick reply. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.