angular load local json file via services

前端 未结 1 1502
暗喜
暗喜 2021-02-10 13:39

I am trying to load a local json file within the same directory as my service file.

No JS errors and under the Net tab, I can see that the json file loaded.

Yet

相关标签:
1条回答
  • 2021-02-10 14:23

    Is there a reason why you don't use build in $http service to fetch JSON? It can be simpler with it:

    webTestApp.factory('webtest', function($timeout, $http) {
        var Webtest = {
            fetch: function() {
                return $timeout(function() {
                    return $http.get('webtest.json').then(function(response) {
                        return response.data;
                    });
                }, 30);
            }
        }
    
        return Webtest;
    });
    

    and in controller:

    webtest.fetch().then(function(data) {
        $scope.data = data;
    });
    

    Here is fixed code:

    http://plnkr.co/edit/f1HoHBGgv9dNO7D7UfPJ?p=preview

    Anyway, you problem was that you returned promise but never resolved (deferred.resolve) it. in this line

    promised.then(callback(static_obj))
    

    you don't resolve promise but manually invoke callback with some data. It worked because in case of hardcoded json object it's already available in page, but in case of ajax request you tried to call it before response has come. So you would need to move promised.then(callback(static_obj)) into onreadystatechange function. But if you go with this way you don't need deferred and promise at all, you just use callback.

    0 讨论(0)
提交回复
热议问题