Unknown User
Unknown User

Reputation: 3668

Unable to access the promise returned

New to AngularJS.

I'm trying to get data from a JSON file through $http and $q and append the data to the view.

But I'm unable to do it. Only 3 li elements are created whereas the JSON data has 6 records.

I want to do this using a promise, but it's not working.

This Plunker demonstrates the issue.

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

Thanks in advance.

Upvotes: 1

Views: 73

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

You need to access the data from the resolved promise using then()...

messageData.getMessageData().then(function (data) {
    $scope.messages = data;
}, function (errorStatus) {
    $scope.errorStatus = errorStatus;
});

You can also simplify the service a bit by using the promise returned by $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;
                });
        }
    }
});

Upvotes: 3

Related Questions