Codehan25
Codehan25

Reputation: 3014

AngularJS (Loading JSON with custom Service)

I'm trying to built a service for loading json files. What am I doing wrong?

The Service

app.service("jsonService", function ($http, $q)
{
    var deferred = $q.defer();

    $http.get('./assets/json/home.json').then(function (data)
    {
        deferred.resolve(data);
    });

    this.getHomeItems = function ()
    {
        return deferred.promise;
    }
})

My Controller

app.controller('homeController', function ($scope, jsonService) {

    var promise = jsonService.getHomeItems();
    promise.then(function (data)
    {
        $scope.home_items = data;
        console.log($scope.home_items);
    });

});

Console Error: $scope is not defined

Upvotes: 0

Views: 1176

Answers (3)

aenea
aenea

Reputation: 21

Without looking at the HTML, which you did not provide, I reckon you may not have injected the $scope into your controller constructor:

app.controller('homeController', ['$scope', function ($scope,  jsonService) {
    ...
}]);

Theoretically, AngularJS should be able to infer the dependency from the variable name, but according to the official documentation there are circumstances where this does not work and the practice of not explicitly injecting dependencies is discouraged. So you may want to try explicit injection (as shown above).

See the examples on the official docs here:

https://docs.angularjs.org/guide/controller

and here:

https://docs.angularjs.org/guide/di

Upvotes: 1

Martin
Martin

Reputation: 16300

You are have a common anti-pattern where you are unwrapping the promise returned by $http and then re-wrapping the data in a promise. This is unnecessary, just return the promise returned by $http.

this.getHomeItems = function () {
    return $http.get("./assets/json/home.json");
}

Upvotes: 0

κροκς
κροκς

Reputation: 590

You are missing the dependency injection.

Your service should be:

app.service("jsonService", ["$http", "$q", function ($http, $q)
{
    var deferred = $q.defer();

    $http.get("./assets/json/home.json").then(function (data)
    {
        deferred.resolve(data);
    });

    this.getHomeItems = function ()
    {
        return deferred.promise;
    }
}]);

And your Controller:

app.controller("homeController", ["$scope", "jsonService", function ($scope, jsonService)
{
    var promise = jsonService.getHomeItems();
    promise.then(function (data)
    {
        $scope.home_items = data;
        console.log($scope.home_items);
    });
}]);

Upvotes: 2

Related Questions