Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem?
Service: Below is the code that my controller 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:
I am confused because despite the service logging Array[7]
containing the required data to the console during the API call's .then()
, I am unable to access it in the controller. When debugging, I receive 'undefined'
.
Controller: While executing the same code present in the service's getBoatList
, everything functions correctly. However, when trying to retrieve the return data from activate()
, I only receive '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: Even though the service is fetching and displaying the correct data on the console, the controller is unable to access the same information. How can I resolve this issue, and what misconception might be leading to this problem?