I'm rather confused over the difference between a factory and a service and why one would choose one over the other. Here I have a factory but is it possible to write as a service and if so what would it look like? Also what's the advantage of using a service or a factory here?
app.factory('testInterceptor', ['$q', function ($q) {
return {
'request': function (config) {
return config;
},
// optional method
'requestError': function (rejection) {
return $q.reject(rejection);
},
// optional method
'response': function (response) {
return response;
},
// optional method
'responseError': function (rejection) {
return $q.reject(rejection);
}
}
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('testInterceptor');
}])
Related
I have service which make post request and returns a data.
app.service('flagService', ['$http', function ($http) {
this.getData = function (r, c) {
return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) {
return data;
})
}
}]);
And somewhere in the controller
flagService.getData(row, column).then(function () {
console.log('it works')
})
But api can also return 500 status code. In this case I get "posssible unhandled rejection..." in the console. Now I would like to make simple alert() which will open when 500 error is returned. I've tried many, many solutions including second function, .catch(), .error().
app.service('flagService', ['$http', function ($http) {
this.getData = function (r, c) {
return $http.post('http://localhost:8080/api/flag', { row: r, column: c }).then(function (data) {
return data;
}, function (error) {
console.log(error)
}).catch(function () {console.log('error')}).error(function() {console.log('error')})
}
}]);
But I still can't hadle error. Any solution? Thanks!
You can use interceptors for global error handling, responseError will be called whenever request is resolved with a rejection.
.factory('myInterceptor', ['$q', '$location', '$injector', function ($q, $location, $injector) {
return {
response: function (response) {
return response || $q.when(response);
},
responseError: function (rejection) {
if (rejection.status === 500) {
console.log('http 500 response')
}
return $q.reject(rejection);
}
}
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
I need to call one of my AngularJS function on every Ajax request that my application makes and I want to do it AngularJS Way (not a classic JS/JQuery Way)
Here is my code :
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
return {
'request': function(request) {
// My angularJS Function goes here.
return request;
},
'responseError': function(response) {
return $q.reject(response);
}
};
}]);
}])
but it's not working some how.
No Error - No output on console. Help is highly appreciated.
Found duplicate $httpProvider.interceptors causing this issue. Fixed, now it's working fine.
Try this one
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
var requestPromise = {
request: function(request) {
// My angularJS Function goes here.
return request;
},
responseError: function(response) {
return $q.reject(response);
}
};
return requestPromise;
}]);
}])
Is it possible to set a default action for $http in my app?
The idea would be that if any $http call in a controller, or service of my app would return 405, I could change to state 'login'
Something like this (of course this will not work at all, but I guess that shows the idea)
angular.module('app',[]).config(function($http){
$http.error(function(error,state){
if (state===405){
do stuff
}
);
You can use interceptors to achieve this.
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});
Read more about it here
You should do something like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
//Do whatever you want on success
}, function errorCallback(response) {
if(response.status == 405) {
//Go to login
}
});
Below code might help you:
$http.get("url")
.success(function (data, status, headers, config) {
$scope.content = data;
if (data == '405') {
$state.go('login', {id: the_necesarry_id});
}
else {window.alert(' ');}
})
.error(function (data, status, headers, config) {
});
use angularjs Interceptors
// interceptors.js
.factory('httpInterceptor', function ($q, $injector) {
return {
'requestError': function(rejection) {
// do something on error
if(rejection.status === 405){
$injector.get('$state').transitionTo('login');
}
return $q.reject(rejection);
},
'responseError': function(rejection) {
// do something on error
if(rejection.status === 405){
$injector.get('$state').transitionTo('login');
}
return $q.reject(rejection);
}
};
});
// app.js
app.config( function ($httpProvider, $interpolateProvider, $routeProvider) {
$httpProvider.interceptors.push('httpInterceptor');
...
});
ExpressJS is sending the following response...
res.send('ItemUploaded');
I'm trying to get AngularJS to see this response via an Interceptor and perform a redirect. Does anyone have sample code where Angular catches a server response (such as my "ItemUploaded") and performs a redirect to a partial (via $location)?
This works fine. I have used it in my application.
var interceptor = function ($q, $location) {
return {
request: function (config) {//req
console.log(config);
return config;
},
response: function (result) {//res
console.log('Repos:');
console.log(result.status);
return result;
},
responseError: function (rejection) {//error
console.log('Failed with', rejection.status, 'status');
if (rejection.status == 403) {
$location.url('/dashboard');
}
return $q.reject(rejection);
}
}
};
module.config(function ($httpProvider) {
$httpProvider.interceptors.push(interceptor);
});
Here is the factory for the interceptor:
.factory('InterceptorService',['$q', '$location', function( $q, $location, $http){
var InterceptorServiceFactory = {};
var _request = function(config){
//success logic here
return config;
}
var _responseError = function(rejection) {
//error here. for example server respond with 401
return $q.reject(rejection);
}
InterceptorServiceFactory.request = _request;
InterceptorServiceFactory.responseError = _responseError;
return InterceptorServiceFactory;
}]);
then register the interceptor:
.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push('InterceptorService');
}]);
Every request coming will be passed here.
You can implement a interceptor factory which will redirect if it gets a matching result.
angular
.module('app')
.factory("httpinterceptor", ["$location",
function(location) {
return {
'response': function(response) {
if (response.data === "ItemUploaded") {
location.path("/ItemUploaded")
}
}
}
}
]);
$provide.factory('myHttpInterceptor', function($q) {
return {
// optional method
'request': function(config) {
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
console.log(config);
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
//if (canRecover(rejection)) {
// return responseOrNewPromise;
//}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
I want when client request file '.html', it won't call to server ever. Instead I will use requireJS. How can I response this data from requirejs to client?