0

I'm trying to get data from a REST service and display the elements in the browser. Piece of code:

Server.prototype.typeNames = function() {
                var json = '{'
                        + '"query" : "MATCH n RETURN n.typeName LIMIT 10"'
                        + '}';
                $http.post("http://localhost:7474/db/data/cypher", json).then(function(response) {
                    var data = response.data;
                    console.log(data);
                    return data;
                });
            }

I'm sure the JSON and the REST call are correct because I can see the data in my console and it's correct but I can't see it on the page. I have also this in my js file:

$scope.typeNames = Server.typeNames()

In HTML:

{{typeNames}}

Also: I install AngularJS debug extension for chrome and there it's also null:

typeNames: null

Here (http://pastebin.com/itHv97da) you can find a bigger part of code. This code is not mine, the Server.prototype things were all there. I just added the Server.prototype.typeNames and I'm trying to get it to work.

Joachim
  • 173
  • 1
  • 8

3 Answers3

1

Your typeNames function isn't returning anything.

Depending on the version you can try returning the whole $http part, but even a better way would be to return a promise, and have the promise resolved within the .then callback.

Something like this:

var deferred = $q.defer();
$http.post("http://localhost:7474/db/data/cypher", json).then(function(response) {
    var data = response.data;
    console.log(data);
    deferred.resolve(data); // <--- this is the key
    return data;
});
return deferred.promise;
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • the `$http.post` isn't already a deferred objecT? why do we need to add another promise in the `then` then? – Patrick Ferreira Jun 24 '14 at 09:30
  • @PatrickFerreira I wasn't sure if it was so in every version (that's why I wrote that in my second sentence)... but even so, OP needs to return something from the `typeNames` function (`return $http.post...`) or just assign the response data to the scope variable, if it's the proper scope. – Shomz Jun 24 '14 at 09:43
0

Since it's an async call you need to work with promises, some samples:

Processing $http response in service

More info about how promises work:

http://andyshora.com/promises-angularjs-explained-as-cartoon.html

Community
  • 1
  • 1
Braulio
  • 1,748
  • 14
  • 23
0
Server.prototype.loadTypeNames = function(typeNames) {
  var json = {query : 'MATCH n RETURN n.typeName LIMIT 10'};

  $http.post("http://localhost:7474/db/data/cypher", json).then(function(response) {
      typeNames = response
  });
}

in Your js file:

$scope.typeNames = [];
Server.loadTypeNames(typeNames);
Artur Boruński
  • 527
  • 1
  • 3
  • 4