Search code examples
angularjsservicestack-text

How to return inner array of items from $http / JSON with AngularJS?


I'm trying to return the items from a JSON response and cannot figure out the syntax. The response is a custom ServiceStack DTO (notice the inner array, called "Items"):

{"Items":[{"Id":"ABC1234","Name":"Tests-TestItem01","Desc":"Test Item 01"}]}

I have a AngularJS service with a method getAll():

    function getAll() {
        return $http.get('http://servername.com/TestItems/GetAll')
            .then(getAllComplete)
            .catch(function(message) {
                exception.catcher('XHR Failed for Applications')(message);
                $location.url('/');
            });

        function getAllComplete(data, status, headers, config) {
            //return data.data[0].data.results;
            logger.info(data[0]);
            return data[0];
        }
    }

And I have a controller that is trying to use this service:

(function () {
    'use strict';

    angular
        .module('testmodule')
        .controller('TestModule', TestModule);

    function TestModule(testItemSvc, logger) {
        var vm = this;
        vm.testItems = [];
        vm.title = "Test Items";
        vm.activate = activate;

        activate();

        function activate()
        {
            return getTestItems().then(function(){
               // Log and announce
                logger.info('Test Items loaded');
            });
        }

        function getTestItems(){
            return testItemSvc.getAll().then(function(data){
                vm.testItems = data;
                return vm.testItems;
            });
        }
    }
})();

I can see the response coming back (which is where I obtained the JSON) but I cannot determine how to return the items. That's where all of the fumbling was in getAllComplete().

Edit:
I added an activate() function and a toastr popup to show when the promise was successfully filled. It DOES fire. And, inside of my view HTML I am successfully binding to vm.title. However, I am using ng-repeat to loop through vm.testItems and it never shows anything.


Solution

  • $http.get returns a promise of an object with the properties that you have listed as function parameters. Try the following

    function getAll() {
        function errorHandler (message) {
            exception.catcher('XHR Failed for Applications')(message);
            $location.url('/');
        }
    
        function successHandler(response) {
            return response.data.Items;
        }
    
        return $http.get('http://servername.com/TestItems/GetAll')
            .then(successHandler, errorHandler);
    }