【问题标题】:Loading a JSON file trough an angular service通过角度服务加载 JSON 文件
【发布时间】:2016-12-04 21:50:18
【问题描述】:

我想从控制器“menuBarCtrl”调用 Angular 服务函数“getDecks()”。在 getDecks() 返回我的 JSON 文件的内容后,我想将文件的内容存储在本地 $scope 变量中。

但是,如果我尝试在控制台中显示该值,我只会得到一个“未定义”。

ajapp.controller('MenuBarCtrl', function($scope, $http, CardProvider) {

    $scope.decks = CardProvider.getDecks();

    console.log($scope.decks);

});

ajapp.service('CardProvider', function($http) {

    this.getDecks = function(){

        var json;
        $http.get('content/SetList.json').success(function(data, status){

            json = data;
        }).error(function (data, status) {
            alert("File Request Failed ["+status+"]");
        });

        return json;
    }
});

【问题讨论】:

  • $http.get 函数中尝试return 语句。
  • 你知道 Promise 是如何工作的吗...?

标签: javascript angularjs json


【解决方案1】:

问题不在于角度,而在于 JS 的异步性。

这似乎是您想要实现的目标:

ajapp.controller('MenuBarCtrl', function($scope, $http, CardProvider) {
    CardProvider.getDecks()
    .then(function(data) {
        $scope.decks = data;
    })
    .catch(function (data, status) {
        /* handle error*/
    });
});

ajapp.service('CardProvider', function($http) {
    this.getDecks = function(){
        return $http.get('content/SetList.json');
    }
});

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2014-02-01
    • 2019-12-15
    • 2020-02-25
    相关资源
    最近更新 更多