我想創建一個模擬練習來幫助我的同事們理解AngularJS。在我的例子中,我希望調用一個服務來提供一個對象數組,我們將把它傳遞給一個控制器,並分配給一個$scope
變量(我創建的例子是提供關於披頭士的信息)。我不想爲我的示例構建REST服務,因此我只是要從服務中返回靜態/硬編碼的對象數組。然而,我從服務返回的是不是一個承諾,因此我不能使用.then()
方法,或者我應該說,當我嘗試使用它時會出現錯誤。。然後不是一個函數 - 爲AngularJS做一個簡單的函數承諾
TypeError: AlbumsService.fetchBeatlesAlbums(...).then is not a function
因爲我們使用.then()
通過$http
提供數據時,我想用.then()
所以它是類似於現實世界的應用程序。有什麼辦法可以解決這個問題嗎?下面是我的控制器和我的服務......我有評論發生錯誤:
angular.module('beatlesApp', []) // First we state the app name, followed by an array of dependancies
// here is our controller...
.controller('MainCtrl', ['$scope', function($scope) {
// here we can set our $scope variables
}])
.controller('ChildCtrl', ['$scope', 'AlbumsService', function($scope, AlbumsService) {
// here we can set our $scope variables
// HERE WE GET AN ERROR... AlbumsService.fetchBeatlesAlbums(...).then is not a function
AlbumsService.fetchBeatlesAlbums().then(function(resp) {
$scope.albums = resp;
});
}])
// This is a service that provides data, in a real world app we would get the data from $http sources
.service('AlbumsService', function() {
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'
}];
};
});
您的'fetchBeatlesAlbums'返回一個數組。那麼你期望什麼? – Bergi
你可以使用$ q服務返回一個承諾,並用你的數據數組調用'resolve' – Alessio
那麼,你使用'$ q'並返回一個承諾?!我投了'-1',因爲你的問題沒有任何研究工作;很容易谷歌如何可以返回一個承諾。 – dirkk