To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Instead of building a REST service, I plan to return a static / hard coded Object Array from my service. However, the service does not return a promise which causes an error when trying to use the .then() method.
TypeError: AlbumsService.fetchBeatlesAlbums(...).then is not a function
In typical data retrieval using $http, we would utilize .then(), so I want to find a way to simulate this behavior in my exercise. Below are the controllers and service with comments indicating where the error occurs:
angular.module('beatlesApp', []) // Defining the app name and dependencies
.controller('MainCtrl', ['$scope', function($scope) {
// Setting $scope variables
}])
.controller('ChildCtrl', ['$scope', 'AlbumsService', function($scope, AlbumsService) {
// Setting $scope variables
// ERROR OCCURS HERE... AlbumsService.fetchBeatlesAlbums(...).then is not a function
AlbumsService.fetchBeatlesAlbums().then(function(resp) {
$scope.albums = resp;
});
}])
.service('AlbumsService', function() {
// Service providing data - data is hardcoded for this example
this.fetchBeatlesAlbums = function() {
return [{
name: 'Please Please Me',
released: '1963',
pic: 'please.jpg'
}, {
name: 'With the Beatles',
released: '1963',
pic: 'with.jpg'
}, {
name: 'A Hard Day\' s Night',
released: '1964',
pic: 'hard.jpg'
}, {
name: 'Beatles For Sale',
released: '1964',
pic: 'bfs.jpg'
}, {
name: 'Help!',
released: '1965',
pic: 'help.jpg'
}, {
name: 'Rubber Soul',
released: '1965',
pic: 'rubber.jpg'
}, {
name: 'Revolver',
released: '1966',
pic: 'revolver.jpg'
}, {
name: 'Sgt Pepper\'s Lonely Hearts Club Band',
released: '1967',
pic: 'splhb.jpg'
}];
};
});