无法访问返回的承诺

时间:2014-07-15 17:15:40

标签: javascript json angularjs promise

AngularJS新手。

我正在尝试通过$http$q从JSON文件中获取数据,并将数据附加到视图中。

但我无法做到。仅创建了3个li元素,而JSON数据有6个记录。

我想使用诺言做到这一点,但它不起作用。

Plunker证明了这个问题。

HTML:

<div class="container" ng-controller="dataCont">        
    <input type="text" name="text-field" id="text-field"/>
    <ul>
        <li ng-repeat="msg in messages">                
            {{ msg.name }}
        </li>
    </ul>
</div>

App.js:

"use strict";
var App = angular.module('app', []);

App.controller('dataCont', function($scope, messageData) {
    $scope.messages = messageData.getMessageData();
    // console.log($scope.messages);
})

Services.js:

App.factory('messageData', function($http, $q) {
    return {
        getMessageData: function() {
            var deferred = $q.defer();

            $http({method: 'GET', url: 'data.json'})
            .success(function(data, status, headers, config) {
                deferred.resolve(data);
            })
            .error(function(data, status, headers, config) {
                deferred.reject(status);
            })

            return deferred.promise;
        }
    }
});

提前致谢。

1 个答案:

答案 0 :(得分:3)

您需要使用then() ...

访问已解决的承诺中的数据
messageData.getMessageData().then(function (data) {
    $scope.messages = data;
}, function (errorStatus) {
    $scope.errorStatus = errorStatus;
});

您还可以使用$ http ...

返回的承诺简化服务
App.factory('messageData', function($http) {
    return {
        getMessageData: function() {
            return $http({method: 'GET', url: 'data.json'})
                .then(function(response) {
                    return response.data;
                }, function(errorResponse) {
                    throw errorResponse.status;
                });
        }
    }
});
相关问题