javascript - 无法使用 AngularJS 中的 HTTP get 调用从 JSON 平面文件返回结果

标签 javascript json angularjs angularjs-directive angularjs-service

我正在尝试从我的代码中删除一个硬编码数组并放入一个我可以随时替换的平面文件中,因此我使用 HTTP get 来执行此操作。

使用下面的代码,它不会以我可以在我的标记中迭代它的方式返回结构。此外,出于某种原因,当我查看 Firebug 并查看请求时,它似乎调用了 4 次(!)。

var app = angular.module('MainEventApp', ['cloudinary']);
app.service('MainEventRepository', ['$http', function ($http) {

    this.$http = $http;

    this.getMainEvents = function () {
        return this.$http.get('/main_events.json').then(function(response) {
            return response;
        });
    }
}]);

app.controller("MainEventCtrl", ['$scope', 'MainEventRepository', function ($scope, MainEventRepository) {       
   $scope.main_events = MainEventRepository.getMainEvents();
}]);

main_events.json

[
    {
        "id": 1,
        "roman_numeral": "I",
        "name": "Hulk Hogan & Mr T vs Rowdy Roddy Piper & Paul Orndorff",
        "venue": "Madison Square Garden",
        "state": "New York",
        "attendance": 19121
    },
    ... and so on ...
]

我的标记:

ng-repeat='main_events in main_events'

最佳答案

在你的 Controller 中,完成 promise :

MainEventRepository.getMainEvents().then(function(data) {
    $scope.main_events = data;
});

此外,在您的服务中,从响应中返回 data 对象:

return response.data;

关于javascript - 无法使用 AngularJS 中的 HTTP get 调用从 JSON 平面文件返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26428983/

相关文章:

javascript - 如何让 css 转换在滚动到视口(viewport)时执行?

javascript - 如何在列表内的同一 li 中附加测试

javascript - 无法访问从 ng-repeat 调用的函数中的用户输入

java - 通过 Java 解析 JSON - 具有键->值格式的数组

java - Jackson 总是序列化完整对象或总是只序列化 id

javascript - jQuery :hover Div to reveal Sibling

ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?

javascript - AngularJS $http 使用参数中的对象访问 ASP.NET Web Api

angularjs - Node API 和 Angular App - 了解在 Cookie 中存储 JWT

angularjs - 使用 Angular-Wakanda 进行文件上传