PANDA Stack
PANDA Stack

Reputation: 1363

AngularJS: Why does my controller get 'undefined' from my service call?

Question: My service is retrieving the proper information, so why isn't my controller getting data from my service?

Service: This is the code my controller (and eventually other things) calls.

// search.service.js
(function () {
    'use strict';

    angular.
        module('trips').
        factory('SearchService', SearchService);

    SearchService.$inject = ['BoatList'];

    function SearchService(BoatList) {
        var service = {
            getBoatList: getBoatList
        };

        return service;

        //////////////////////

        function getBoatList() {
            BoatList.query()
                .$promise
                .then(function (data) {
                    console.log(data);
                    return data;
                })
                .catch(function (error) {
                    return error;
                })
        }
    }
})();

Console Information:

This is why I'm so confused. The service logs Array[7] to the console as part of the .then() in the API call. The array contains the data I want. I can't seem to access it in the controller for some reason. When I run through it with the debugger I get 'undefined'.

Controller: When I call the same code as is in the service's getBoatList everything works just fine. When I try to access the return data from activate() I don't get any errors, just 'undefined'.

//search.controller.js
(function () {
    'use strict';

    angular.
        module('trips').
        controller('SearchController', SearchController);

    SearchController.$inject = ['$stateParams', 'SearchService'];

    function SearchController($stateParams, SearchService) {
        var vm = this;

        vm.boatList = null;

        activate();

        ////////////////////

        function activate() {
            vm.boatList = SearchService.getBoatList();
        }
    }
})();

Recap: My service gets the correct data and logs it to the console. My controller isn't getting the same information by calling the service. How can I fix it, and what misunderstanding is causing me this problem?

Upvotes: 0

Views: 863

Answers (1)

Niezborala
Niezborala

Reputation: 1857

You must to change method in your factory, because method getBoatList should return a promise.

Change your factory method to:

function getBoatList() {
   return BoatList.query().$promise;
}

And in controller you must to change activate method to:

function activate() {
   SearchService.getBoatList()
      .then(function (data) {
         vm.boatList = data;
      })
      .catch(function (error) {
         // do smth on error
      });
}

Upvotes: 3

Related Questions