Chènevis
Chènevis

Reputation: 513

AngularJS don’t get JSON data

I want to get data from a JSON file by using $http.get with AngularJS. I use the "new way" to write AngularJS scripts (link).

PLUNKER

Nothing happens, Firebug tells me nothing.

I think the problem is in my activate() function code, I don’t really understood the promises.

function activate() {
    return $http.get('test.json').then(function(data) {
        vm.result = data;
        return vm.result;
    });
} 

Have you an idea about this ?

Upvotes: 2

Views: 198

Answers (2)

scniro
scniro

Reputation: 16989

You're not able to return at that point in your then callback. Simply return the $http call itself, of which will be a promise, and resolve it. Also, your console should be telling you something like $http is undefined since you did not inject this service properly. Observe the following...

function activate() {
    return $http.get('test.json')
}

[...]

activate().then(function(response) {
    vm.result = response.data;
});

Plunker - demo


Side note - you'll likely want to wrap activate() into an reusable service to keep this logic out of our controllers, so we'll instead inject the defined service into controller instead of $http directly.

Plunker - demo with this logic wrapped in a simple service

Upvotes: 2

nbering
nbering

Reputation: 2800

I see a couple of problems.

First, in your plunker code you have:

controller.$inject = ["$http"];

function controller() {

You are missing the $http parameter in your controller function signature.

function controller($http) {

Once I fixed that, I found your index.html page was binding to {{c.value}}, but your controller never defines a value property. Maybe this should be {{c.result}}? If I make these changes I get a visible result.

Upvotes: 2

Related Questions