Ad

$http Is Undefined In Service Despite Injecting It

- 1 answer

I am trying to create a service to provide a js api for the integration between my angular app and the server it talks to. However, whenever I try to use $http in the service it is undefined.

The service is instantiated as $scope.broker in my main controller:

function MainCtrl($scope, $http) {

    $scope.broker = new broker();

...

angular
.module('inspinia')
.controller('MainCtrl', ['$scope','$http',MainCtrl])

The service is then used in a controller attached to the same module:

function locations($scope, $http){

console.log($scope.broker.ping);
$scope.broker.ping();

angular.module('sentry.locations', [])
.controller('locations', ['$scope','$http', locations]);

Service Definition:

function broker($http) {

    var baseurl = 'localhost:8000';

    var broker = {};

    broker.ping = function() {
        console.log(this);
        $http({
            method: 'GET',
            url: baseurl + '/hello'
        })
    };

    console.log($http);

    return broker;
};

angular.module('inspinia')
    .factory('broker', ['$http', broker]);

console.log($scope.broker.ping) correctly prints the ping function.
console.log($http) prints undefined

Thanks in advance for any help.

Edit: Added MainCtrl registration after elipses

Ad

Answer

$scope.broker = new broker();

your broker is from new function in your MainCtrl,not injected by angular service,so $http is undefined.

Ad
source: stackoverflow.com
Ad