1
我試圖通過在服務中執行http請求來清理我的控制器,但出於某種原因,我的控制器中的某個函數沒有從服務獲取響應。控制器沒有得到工廠的響應
我有我的控制器此功能,
$scope.addMovie = function() {
addMovie.add().then(function(response){
if(response){
console.log ('Response')
} else {
console.log ('No reposone')
}
});
這是服務,
(function(){
"use strict";
angular.module('addMovieseat')
.factory('addMovie',
function($http, $q){
return{
add: function(){
var deferred = $q.defer();
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
deferred.resolve(data.results);
console.log ('Succes getting data')
} 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.')
deferred.resolve(false);
});
$(".search_results").fadeOut(250);
return deferred.promise;
}
}
})
})();
當我運行從控制器$scope.addMovie
功能控制檯日誌顯示Succes getting data
從服務然後從控制器中的功能No response
。這裏缺少什麼?
//編輯。現在我想從服務中的數據插入到在我的控制器作用域,
$scope.addMovie = function() {
$scope.movieListID = {};
console.log ('empty' + $scope.movieListID)
movieAdd.add()
.then(function(response){
$scope.movieListID = response;
console.log ('Not empty' + $scope.movieListID)
})
.catch(function(response) {
console.log ('No search reposone')
});
}
但控制檯日誌顯示afther「響應確定」一個「不確定」的消息。
謝謝,這表明答覆是成功的。我試圖從JSON請求中插入數據到控制器的作用域中。 '$ scope.movieListID = response; console.log($ scope.movieListID)''但是這會在控制檯中返回一個「undefined」。 –
'$ scope.movieListID'未定義?在什麼時候?工廠運行併成功返回數據後? – macrog
對不起,我沒有發佈我的新的'addMovie'功能。我已將它添加到我的帖子。我嘗試從'$ scope.movieListID'中插入響應中的數據,並在console.log中找到未定義的範圍。 –