AngularJS进行REST调用并在浏览器中显示结果

AngularJS make REST call and display result in browser

本文关键字:浏览器 显示 结果 进行 REST 调用 AngularJS      更新时间:2023-09-26

我正在尝试从REST服务获取数据,并在浏览器中显示元素。一段代码:

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;
                });
            }

我确信JSON和REST调用是正确的,因为我可以在控制台中看到数据,它是正确的但我在页面上看不到它。我的js文件中也有这个:

$scope.typeNames = Server.typeNames()

在HTML:中

{{typeNames}}

另外:我为chrome安装了AngularJS调试扩展,它也是空的:

typeNames: null

在这里(http://pastebin.com/itHv97da)你可以找到代码的更大部分。这段代码不是我的,Server.prototype的东西都在那里。我刚刚添加了Server.prototype.typeNames,我正在努力让它发挥作用。

您的typeNames函数没有返回任何内容。

根据版本的不同,您可以尝试返回整个$http部分,但更好的方法是返回promise,并在.then回调中解析promise。

类似这样的东西:

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;

由于这是一个异步调用,您需要使用promise,因此一些示例:

正在处理服务中的$http响应

关于承诺如何运作的更多信息:

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

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
  });
}

在您的js文件中:

$scope.typeNames = [];
Server.loadTypeNames(typeNames);