Implement a middleware in angular ui-router - javascript

Scenario:
user opens /myapp/recovery/:token which would call a middleware which would in turn redirect the user either to 'verify' state or 'reset-pwd' state.
these two have a screen while the recovery middleware (router/proxy/etc) won't it just redirects
How can I achieve such a functionality in angular 1.3 using ui-router?
Thanks
Edit
This is what I did, and it seems to be working, but I'm unsure if it's the best solution.
config.js
$stateProvider.state('account-recovery', {
url: '/account-recovery/:token',
controller: 'AccountRecovery'
});
$stateProvider.state('verify', { ... });
$stateProvider.state('reset-pwd', { ... });
And in
account-recovery.js
class AccountRecovery {
static get $inject() {
return ['$state' ...];
}
constructor($state, ...) {
this.$state = $state;
this.token = this.$state.params.token || '';
this.doSomeAsync();
}
async doSomeAsync() {
try {
const response = await getSomethingFromServer();
if (response == null || response.data == null) {
console.error('No response');
}
const user = response.data;
if (user.this) {
this.$state.go('reset-pwd');
}
else if (user.that) {
this.$state.go('verify');
}
}
catch (err) {
console.error(err);
}
}
}

Use the run function for the main module:
angular
.module('myApp')
.run(runFn);
runFn.$inject = ['$rootScope', '$state', 'myService'];
function runFn($rootScope,$state, myService) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
//In here you can use the $state service , i.e.
//if(toState.name === 'account-recovery'){
// myService.getUser().then(function(user){
// if(user){
// $state.go('reset-pwd')
// }
// else{
// $state.go('verify');
// }
//});
});
}

Related

angularjs authentication using $locationChangeStart

I'm authenticating an angular app code given below, Basically I'm checking token from backend called if token is valid then we can allow users to view allowed page.
It's working somewhat but problem is when I'm going to /jobs page is somewhat loading then redirecting to login page but i don't want to show jobs page initially for few seconds it should be redirect quickly or it will not load jobs page.
In app.js
var app = angular.module('ttt', ['ui.router', 'ui.bootstrap', 'ngResource', "ngStorage", "ngProgress", "ngCookies", 'angular-jwt', 'ngLodash','tagged.directives.infiniteScroll']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', "$httpProvider", function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise(function ($stateParams) {
console.log("val check", $stateParams, window.location);
window.location.href = "/undefined";
});
$stateProvider.state("jobs", {
url: "/jobs",
templateUrl: "views/dashboard.html",
controller: "JobController as JobCtrl",
resolve : {
formInfo : ["AuthService",function (AuthService) {
return AuthService.getFormInfo();
}]
}
}).state("undefined", {
url: "/undefined",
templateUrl: "views/pagenotfound.html",
bodyClass: "errors errors-404 errors-centered"
}).state("login", {
url: "/login",
templateUrl: "views/login.html",
controller: "LoginController as LoginCtrl",
resolve : {
formInfo : ["AuthService",function (AuthService) {
return AuthService.getFormInfo();
}]
}
})
}]);
app.run(['$rootScope', 'ngProgressFactory', '$state', '$compile', '$location', '$cookies', 'jwtHelper','AuthService', function ($rootScope, ngProgressFactory, $compile, $state, $location, $cookies, jwtHelper,AuthService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
$rootScope.progressbar = ngProgressFactory.createInstance();
$rootScope.progressbar.start();
$rootScope.location = $location;
});
var authPreventer = $rootScope.$on('$locationChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
var notCheckRoute = ["/undefined", "/signin", "/login"];
//event.preventDefault();
if(notCheckRoute.indexOf($location.path()) !== -1){
AuthService.checkPermission()
.then(function(data) {
//event.preventDefault();
if(data.active){
$location.path('/home');
}else{
$location.path('/login');
}
});
}else{
//event.preventDefault();
AuthService.checkPermission()
.then(function(data) {
if(!data.active){
$location.path('/login');
}else{
//$location.path('/jobs');
}
});
}
});
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
$rootScope.progressbar.complete();
$rootScope.bodyClass = toState.bodyClass;
});
$rootScope.$on('$stateChangeError', function (event) {
//$state.go('undefined');
});
}]);
In service
app.service('AuthService',['jwtHelper','$cookies','$location','$window','$http','$q',function (jwtHelper,$cookies,$location,$window,$http,$q) {
this.login = function (token){
var payload = jwtHelper.decodeToken(token);
};
this.logout = function (data) {
};
var validatetoken = undefined;
this.checkPermission = function () {
if (!validatetoken) {
// create deferred object using $q
var deferred = $q.defer();
// get validatetoken form backend
$http.post('/api/validatetoken', {token: $cookies.get('token')})
.then(function(result) {
// save fetched validatetoken to the local variable
validatetoken = result.data;
// resolve the deferred
deferred.resolve(validatetoken);
}, function(error) {
validatetoken = error;
deferred.reject(error);
});
// set the validatetoken object to be a promise until result comeback
validatetoken = deferred.promise;
}
return $q.when(validatetoken);
}
this.getFormInfo = function () {
return $http.get("/api/getloginurl");
}
}]);
i don't want to show jobs page initially for few seconds it should be redirect quickly or it will not load jobs page.
When using the ui-router, avoid putting code in the $locationChangeStart block. This will cause conflicts with ui-router operation.
To prevent the jobs page from loading, check the authorization in the resolver for the state.
$stateProvider.state("jobs", {
url: "/jobs",
templateUrl: "views/dashboard.html",
controller: "JobController as JobCtrl",
resolve : {
formInfo : ["AuthService",function (AuthService) {
return AuthService.getFormInfo();
}],
//CHECK permission
permission: ["AuthService", function (AuthService) {
return AuthService.checkPermission()
.then(function(data) {
if(!data.active){
return data
} else {
//REJECT if not authorized
throw "Not Authorized";
};
}).catch(function(error) {
console.log("ERROR");
throw error;
});
}];
}
})
By rejecting the resolve, the state change will be aborted and the page will not load.
Update
I can put in resolve state but if we have more state for example we have 50 different URL then every time do we have to put permission:
["AuthService", function (AuthService) {
return AuthService.checkPermission()
.then( function(data) {
if(!data.active){
return data
} else {
//REJECT if not authorized throw "Not Authorized";
};
}).catch( function(error) {
console.log("ERROR");
throw error;
});
All of that code can be re-factored into a service:
app.service("permissionService",["AuthService", function (AuthService) {
this.get = function () {
return AuthService.checkPermission()
.then( function(data) {
if(!data.active){
return data
} else {
//REJECT if not authorized
throw "Not Authorized";
};
}).catch( function(error) {
console.log("ERROR");
throw error;
});
};
}]);
Then use it in each resolver:
//CHECK permission
permission: ["permissionService", function (permissionService) {
return permissionService.get();
}];
By re-factoring the code, the resolver can be greatly simplified.

How to get username of currenlty logged on user authservice

I would like to get the currently loged in username so i can display it. But i dont know how to do it ? Any ideas ? I am using authservice Here is my angular controller in which i would like to get the username.
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my main angular controller code
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my second angular code :
var app = angular.module('myApp');
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
$scope.gotoregister = function () {
$location.path('/register');
};
$scope.gotoprive = function () {
$location.path('/prive');
};
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
and my services
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http) {
// create user variable
var user = null;
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
So this should probably work, maybe you will need to make some small adjustments because i don't know how exactly is your app structured, but this will work.
First you need to change your AuthService to look like this
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
after that changes in authService, you must make this on your app run, so each time application run (refresh) it first check coockie to see if there is active session(member) and if there is it will set it inside our AuthService.
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
And simply anywhere where you want to get auth member you have to do this, first include in your controller/directive AuthService and do this
AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
});
I hope this helps you, if you find any difficulties i'm happy to help
just a demo example
in login controller
var login = function(credentials) {
AuthService.login(credentials).then(function(result) {
var user = result.data;
AuthService.setCurrentUser(user);
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
}).catch(function(err) {
if (err.status < 0) {
comsole.error('Please check your internet connection!');
} else {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
}
});
};
in AuthService
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
}
}
return service;
});
in the controller which attached with your dashboard view
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.fullName = AuthService.getFullName();
vm.currentUser = AuthService.getCurrentUser();
}
});
There are few methods how you can get currently logged user, it mostly depends on you app structure and API, you probably should have API end point to get authenticated member and that call is made on each app refresh.
Also if you can show us your authservice.
Edit:
Also on successful login you can store information about logged user in coockie like this
function doLogin(admin) {
return authMemberResources.login(details).then(function(response) {
if (response) {
$cookies.putObject('loginSession', response);
} else {
console.log('wrong details');
}
});
So basically you can use angularjs coockies service and make loginSession coockie like that, and on app refresh or anywhere where you need logged user info, you can get that like this:
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
console.log(session);
}
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
},
getAuthenticatedMember: function() {
if ($cookies.get('currentUser')) {
return JSON.parse($cookies.get('currentUser'));
}
}
}
return service;
});
That should work, i added new function getAuthenticatedMember and you can use it where you need it. And you can use it like this:
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.currentUser = AuthService.getAuthenticatedMember();
}
});

Karma - Spied function error handling

I have a service like this:
app.service('usersService.v2', ['$http', '$q', '$exceptionHandler', 'User', 'userValidator.v2', 'CRUD', function($http, $q, $exceptionHandler, User, userValidator, CRUD){
function dummyPromise(){
var dummyDeferred = $q.defer();
dummyDeferred.resolve('dummy');
return deferred.promise;
}
this.getUser = function(userID, companyID){
try{
userValidator.validateId(userID);
userValidator.validateId(companyID);
}
catch(e){
$exceptionHandler(e);
return dummyPromise();
}
return $http.get(apiUrl + 'api/v2/companies/' + companyID + '/users/' + userID)
.then(function(response){
var user = new User(response.data);
try{
userValidator.validateUser(CRUD.READ, user);
}
catch(e){
$exceptionHandler(e);
return;
}
return user;
})
};
}]);
And basically I want to test the behaviour of this service depending on what the validation functions do.
userValidator.* function are if/else blocks throwing errors.
In Karma I have something like this:
describe('Service: usersService.v2', function () {
var usersService, httpBackend, state, userValidator;
const url = 'address'
function _inject() {
angular.mock.inject(function ($injector) {
usersService = $injector.get('usersService.v2');
userValidator = $injector.get('userValidator.v2');
httpBackend = $injector.get('$httpBackend');
});
}
beforeEach(function () {
angular.mock.module('app');
_inject();
});
describe('getUser', function () {
beforeEach(function () {
httpBackend.when('GET', url);
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should return a dummy promise if ID validation fails', function(){
spyOn(userValidator, 'validateId').and.throwError('Missing or wrong ID thrown');
usersService.getUser()
.then(function(data){expect(data).toBe('dummy');})
});
)};
})
but when I'm running Karma I get an error, as it would be if I didn't put the catch to handle the expection and the following block of code is not executed.
What am I doing wrong?
Cheers,
Manuel
UPDATE:
Validate methods are something like this:
... code code code ...
this.validateId = function(ID){
if(!ID || !angular.isNumber(ID)) throw 'Missing or wrong ID';
}
Thus my problem is that Karma is trying to handle the error thrown by validation instead of let the userService do it.
You are testing usersService.v2.You can not test the userValidator.v2 at the same time.But you can mock the userValidator.v2 service.
var userValidator;
beforeEach(function() {
module(function($provider) {
userValidator = {
validateId: function(id) {
if (id === 123 ||id === 456 ) { //put your mock test id here for PASS case
return true
}
return false;
}
}
$provider.value('userValidator.v2', userValidator);
})
});
describe('getUser', function () {
beforeEach(function () {
httpBackend.when('GET', url)
.respond(200, {
data: "dummy"
});;
});
it('should return a dummy promise if ID validation fails', function() {
usersService.getUser(9879,8798) //Its FAILED case
.then(function(data) { expect(data).toBe('dummy'); })
})
})

Determining whether a user is logged in

when i try to test to redict to api/todo it's not working my condition any idea ?when i try to test to redict to api/todo it's not working my condition any idea
app.js
.run(function ($rootScope, $location,$log,User) {
$rootScope.$on("$routeChangeStart", function (event,next, current) {
if (!User.signin() && next.authenticate === true){
// User isn’t authenticated
$location.path('/signin');
}
});
service.js
signin: function(data){
return $sails.post('/api/auth',data);
},
Controller
.controller('SigninCtrl', function ($scope,$location,User,$http) {
$scope.signin = function(){
var data={ email:$scope.email,password:$scope.password}
var user=User.signin(data);
//console.log(typeof user);
user.success(function (data) {
//console.log("token signin",data);
var token=data.token;
localStorage.setItem('id_token', token);
$location.path("/todo");
})
.error(function (data) {
//Do whatever is needed
//console.log(data);
});
}
});

Interceptor not working

Im trying to make a Interceptor in AngularJS. I'm quite new to AngularJS and found some examples of Interceptor, but can't get it to work.
Here I have my app.js file, which have all relevant code. I also have a controller which calls a REST api and get JSONP returned.
First I declare the module and then config it (define the Interceptor). It should now catch all requests and output to console...
Is it wrong to create the Interceptor with app.factory?
var app = angular.module(
'TVPremieresApp',
[
'app.services'
, 'app.controllers'
]
);
app.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor');
});
app.service('MessageService', function () {
// angular strap alert directive supports multiple alerts.
// Usually this is a distraction to user.
//Let us limit the messages to one
this.messages = [];
this.setError = function(msg) {
this.setMessage(msg, 'error', 'Error:');
};
this.setSuccess = function(msg) {
this.setMessage(msg, 'success', 'Success:');
};
this.setInfo = function (msg) {
this.setMessage(msg, 'info', 'Info:');
};
this.setMessage = function(content, type, title) {
var message = {
type: type,
title: title,
content: content
};
this.messages[0] = message;
};
this.clear = function() {
this.messages = [];
};
});
app.factory('errorInterceptor', function ($q, $location, MessageService, $rootScope) {
return function (promise) {
// clear previously set message
MessageService.clear();
return promise.then(function (response) {
console.log(response);
return response;
},
function (response) {
if (response.status == 404) {
MessageService.setError('Page not found');
}
else if(response.status >= 500){
var msg = "Unknown Error.";
if (response.data.message != undefined) {
msg = response.data.message + " ";
}
MessageService.setError(msg);
}
// and more
return $q.reject(response);
});
};
});
$httpProvider.responseInterceptors are deprecated. You can modify your code
app.factory('errorInterceptor', ['$q', '$rootScope', 'MessageService', '$location',
function ($q, $rootScope, MessageService, $location) {
return {
request: function (config) {
return config || $q.when(config);
},
requestError: function(request){
return $q.reject(request);
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response && response.status === 404) {
}
if (response && response.status >= 500) {
}
return $q.reject(response);
}
};
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
}]);
See Docs for more info

Categories