datapanda datapanda - 6 months ago 20
AngularJS Question

Issue with Angular.js and Angular Style Guide

I'm having an issue correctly getting a data service to work as I try to follow the Angular Style Guide (https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#data-services)

I'm sure it's something obvious to the more experienced but I can't get the data set to assign properly to the vm.items outside of the

Data Service

(function() {
'use strict';

angular
.module('portfolioApp')
.factory('portfolioService', portfolioService);

portfolioService.$inject = ['$http', 'logger'];

function portfolioService($http, logger) {

return {

getPortfolioData: getPortfolioData,

};

function getPortfolioData() {

return $http.get('./assets/portfolio/portfolioItems.json')
.then(getPortfolioDataComplete)
.catch(getPortfolioDataFail);

function getPortfolioDataComplete(response) {
return response.data;

}

function getPortfolioDataFail(error) {

logger.error('XHR Failed for getPortfolioData.' + error.data);
}
}
}
}());


Controller

.controller('portfolioController', ['$scope', '$http', '$stateParams', 'logger', 'portfolioService', function($scope, $http, $stateParams, logger, portfolioService) {

var vm = this;
vm.items = [];

activate();

function activate() {
return getData().then(function() {
logger.info('Activate the portfolio view');

});
}

function getData() {
return portfolioService.getPortfolioData()
.then(function(data) {
vm.items = data;
return vm.items;
});
}

console.log("test")
console.log(vm.items);
console.log("test")

}])

Answer

Your getData function is a promise, so it's run asynchronously. Your onsole.log are called before the end of the promise so the vm.items is still empty.

Try to put the log in the then callback.