Below is my angular controller but in it, my promise doesn't seem to work. console.log isn't showing response nor is alert being shown over here.
myapp.controller('contrl6', ['$scope','$q','$localStorage','$http',
function ($scope,$q,$localStorage,$http) {
$scope.myXhr = function(){
var q = $q.defer();
$http({
method: 'GET',
url: '/api/session_data'
})
.success(function(response){
console.log(response);
q.resolve('request successful');
})
.error(function(response){
console.log("error");
q.reject('ERROR');
});
return q.promise;
}
console.log("hi");
var myPromise = $scope.myXhr();
myPromise.then(function(resolve){
alert(resolve);
console.log(resolve);
}, function(reject){
alert(reject);
console.log(reject);
});
}]);
Inside myxhr
nothing is wired together with the result of $http
. Don't worry about creating a new promise, because $http
already returns one:
$scope.myXhr = function(){
return $http({
method: 'GET',
url: '/api/session_data'
})
.then(function(response){
return response;
})
.catch(function(response){
throw new Error('ERROR');
});
}
Deprecation Notice
The
$http
legacy promise methods.success
and.error
have been deprecated. Use the standard.then
method instead. 1
$scope.myXhrPromise = function(){
return (
$http({
method: 'GET',
url: '/api/session_data'
}).then (function onFulfilled (response) {
console.log(response.data);
//return data for chaining
return response.data;
}).catch (function onRejected (response) {
console.log(response.status);
//throw to chain rejection
throw response;
})
);
};
I copy/pasted your code into a Plunkr and it works just fine once I wire it up correctly.
As Duncan says, make sure you wire it up correctly, using ng-app and ng-controller. If you can update your question with the HTML markup you're using perhaps we can help further.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.