当我在工厂使用控制器调用方法getPopularMovies
时,我的工厂返回undefined,我不知道我在这里做了什么错误,请让我知道
angular.module('ngMovies').factory('moviesFactory', function ($http) {
var movies = [];
function getPopularMovies() {
var popularmoviesurl = "https://api.themoviedb.org/3/movie/popular?api_key=adf3d78d5c0f38313a68de730f02063a";
return $http({method: 'GET', url: popularmoviesurl}).success(function (data, status, headers, config) {
if (status == 200) {
movies = data.results;
} else {
console.error('Error happened while getting the movie list.')
}
}).error(function (data, status, headers, config) {
console.error('Error happened while getting the movie list.')
});
return movies;
}
return {
getPopularMovies: getPopularMovies
}
});
angular.module('ngMovies').controller('popularmoviesController', ['moviesFactory', '$scope', function (moviesFactory, $scope) {
$scope.popularmovies = moviesFactory.getPopularMovies();
}]);
答案 0 :(得分:0)
服务:
angular
.module('ngMovies')
.factory('moviesFactory', function($http) {
function getPopularMovies(callback) {
var popularmoviesurl = "https://api.themoviedb.org/3/movie/popular?api_key=adf3d78d5c0f38313a68de730f02063a";
return $http({
method: 'GET',
url: popularmoviesurl
}).
success(function(data, status, headers, config) {
if (status == 200) {
callback(data.results);
} else {
console.error('Error happened while getting the movie list.')
}
}).
}
return {
getPopularMovies: getPopularMovies
}
});
控制器:
angular
.module('ngMovies')
.controller('popularmoviesController', ['moviesFactory', '$scope', function(moviesFactory, $scope) {
moviesFactory.getPopularMovies(function(movies){
$scope.popularmovies = movies;
});
}]);
答案 1 :(得分:0)
更改您的控制器代码:
angular.module('ngMovies').controller('popularmoviesController', ['moviesFactory', '$scope', function (moviesFactory, $scope) {
moviesFactory.getPopularMovies().then(function(data) {
$scope.popularmovies = data.results;
});
}]);
并且在getPopularMovies
方法中return movies;
语句不是必需的,因为您已经使用相同的方法返回上面的内容。
答案 2 :(得分:0)
我建议使用promises进行异步处理。
moviesFactory.getPopularMovies().then(function(data){
$scope.popularmovies = data;
},function(){
// your error handling
})
然后在控制器内部使用
{
"entityIds" : [12,22,45,2,44,5,66],
"order" : "DESC"
}