I am trying to use the $stateProvider resolve with a factory I created
for some reason, the promise from the factory is an empty object
but when i log the data from the $http call, I get data from my .json file
any idea why my defer.promise is an empty object?
playlistsService.js
(function () {
'use strict';
angular
.module('app.core')
.factory('playlistsService', playlistsService);
playlistsService.$inject = ['$http', '$q'];
/* @ngInject */
function playlistsService($http, $q) {
var service = {
loadPlaylists : loadPlaylists
};
return service;
////////////////
function loadPlaylists() {
var defer = $q.defer();
$http.get('data/playlists.json')
.success(function (data) {
console.log('json data: ' + angular.toJson(data));
defer.resolve(data);
});
console.log('defer.promise: ' + angular.toJson(defer.promise));
return defer.promise;
}
}
})();
playlists.js
(function () {
'use strict';
angular
.module('app.playlists')
.config(stateProvider)
.controller('Playlists', Playlists);
stateProvider.$inject = ['$stateProvider'];
Playlists.$inject = ['playlistsService'];
/* @ngInject */
function stateProvider($stateProvider){
$stateProvider
.state('app.playlists', {
url: '/playlists',
views: {
'menuContent': {
templateUrl: 'app/playlists/playlists.html',
controller: 'Playlists as vm',
resolve: {
playlists: function(playlistsService){
return playlistsService.loadPlaylists();
}
}
}
}
})
}
/* @ngInject */
function Playlists(playlists) {
/* jshint validthis: true */
var vm = this;
vm.activate = activate;
vm.title = 'Playlists';
vm.playlists = playlists;
activate();
////////////////
function activate() {
console.log('playlists object: ' + angular.toJson(vm.playlists))
console.log('playlists from service: ' + angular.toJson(playlists))
}
}
})();
Your Playlists
controller should have $inject
the playlists
promise which has been created in resolve function instead of playlistsService
will do the trick.
Playlists.$inject = ['playlists'];
Update
You could also utilize the promise created by $http.get
instead of create custom promise.
Service
function loadPlaylists() {
return $http.get('data/playlists.json')
.then(function (data) {
console.log('json data: ' + angular.toJson(data));
return data;
});
}
Resolve
resolve: {
playlists: function(playlistsService){
return playlistsService.loadPlaylists();
}
}