I use Restangular
in my angularjs App & use setErrorInterceptor
to handle response error in one place. I want to redirect user to login page if an error occured. I know that the only providers
& constants
are injectable in configuration phase.
var app = angular.module('ourstandApp', ['ngRoute', 'restangular', 'ui.bootstrap', 'ngCookies', 'angularFileUpload']);
// Global configuration
app.config(function (RestangularProvider, baseRequestConfig, $routeProvider, urlsProvider) {
var getBaseRequestUrl = function () {
return baseRequestConfig.protocol + "://" + baseRequestConfig.hostName + ":" + baseRequestConfig.portNumber + baseRequestConfig.resourcePath;
}
var initializeRoute = function () {
$routeProvider.when('/', {
controller: LoginController,
templateUrl: 'views/login.html'
}).
otherwise({
redirectTo: '/'
});
}
initializeRoute();
RestangularProvider.setBaseUrl(getBaseRequestUrl());
RestangularProvider.setErrorInterceptor(function (resp) {
goToLogin(); // i want to change url to login page
return false;
});
});
The idea here is to be more specific about how resources are requested. In this excerpt from a project i am using the
resolve
option ofrouteProvider.when
to look up a resource based on path input and injecting the result asArticleRequest
before resolving the route.If the api calls the route fails and the
$routeChangeError
event is firedHere is a very simple implementation of the
$routeChangeError
handlerand here is the controller
Is something like this usefull in you case with Restangular?
If I understand you correctly you want to redirect the user to a login page based on a status code returned to you by the server? Like a 404 or 403?
If that's the case this is how I handle redirects on a 404 and 403 using
setErrorInterceptor
in one of my apps. This may not be the best way to do this, but It's been working just fine so far for me.the correct way for handling this problem is configuring restangular in
run
method of angularjsInject
$injector
to the config block and invite$location
when needed:Also check my other answers: