Error while calling AngularJS service function in controller? - javascript

I wrote one service which takes a data from one controller and send it to another controller. And this controllers are pointing to different modules. Now when I am calling the service function from both the controller it fires some error.
angular.js:13920 ReferenceError: addData is not defined
at Object.dataservice
Here is my service in pages.module.js
(function ()
{
'use strict';
angular
.module('app.pages', [
'app.pages.auth.login',
'app.pages.auth.login-v2',
'app.pages.auth.register',
'app.pages.auth.register-v2',
'app.pages.auth.verify-mobile',
'app.pages.auth.reset-password',
'app.pages.auth.lock',
'app.pages.coming-soon',
'app.pages.error-404',
'app.pages.error-500',
'app.pages.invoice',
'app.pages.maintenance',
'app.pages.profile',
'app.pages.search',
'app.pages.timeline'
])
.config(config)
.factory('dataservice', dataservice);
/** #ngInject */
function config(msNavigationServiceProvider)
{
// Navigation
msNavigationServiceProvider.saveItem('pages', {
title : 'PAGES',
group : true,
weight: 2
});
}
function dataservice(){
var sendarr = [];
this.addData = function(newObj) {
sendarr.push(newObj);
};
this.getData = function(){
return sendarr;
};
return {
addData: addData,
getData: getData
};
}
})();
this is 1st controller login.controller.js
(function ()
{
'use strict';
angular
.module('app.pages.auth.login')
.controller('LoginController', LoginController);
/** #ngInject */
LoginController.$inject = ['dataservice'];
function LoginController(msApi,$state,dataservice)
{
// Data
var vm = this;
vm.login = login;
vm.startApp = startApp;
vm.fbLogin = fbLogin;
var auth2;
// Methods
function fbLogin(){
FB.login(function(response){
if(response.status=='connected'){
testAPI();
}
else if(response.status == 'not_authorized'){
console.log('error');
}
else{
console.log('please log in');
}
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
});
}
function startApp(){
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '990822731291-21sdd22ujqc78l1q2i2lmf5hfe5satj1.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
fetch_basic_profile: 'true',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customGoogleBtn'));
});
}
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var pushData = [profile.getId(), profile.getName(), profile.getEmail()];
console.log(pushData);
dataservice.addData(pushData);
$state.go('app.pages_auth_verify-mobile')
},
function(error) {
alert(JSON.stringify(error, undefined, 2));
});
}
function login(){
var jsonData = {"mobile":vm.form.mobile};
msApi.request('login.credentials#save',jsonData,
// SUCCESS
function (response)
{
console.log(response.error);
if(response.error == 1){
vm.form.mobileErrorFlag = true;
}
if(response.error == 0){
vm.form.mobileErrorFlag = false;
}
},
// ERROR
function (response)
{
alert(JSON.stringify(response));
}
)
}
}
})();
This one is the 2nd controller verify-mobile.controller.js
(function ()
{
'use strict';
angular
.module('app.pages.auth.verify-mobile')
.controller('VerifyMobileController', VerifyMobileController);
/** #ngInject */
function VerifyMobileController(dataservice)
{
var data = dataservice.getData();
alert(data);
}
})();

You had the methods as this.addData and this.getData in your dataservice whereas you are accessing the same without this in the return. That's why you are getting this error.
You don't need the this inside the factory service and can remove the same as below.
function dataservice(){
var sendarr = [];
var addData = function(newObj) {
sendarr.push(newObj);
};
var getData = function(){
return sendarr;
};
return {
addData: addData,
getData: getData
};
}

Related

Function is not recognized by another function in angularjs

During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}

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();
}
});

Getting 404 not found while creating new json file by Angular $resource

I created a service using ngResource to save the data of form in json format. But after submitting form I got 404 error for 999.json file.
ServiceJS
"use strict";
eventsApp.factory("eventData", function ($resource, $q) {
var resource = $resource("data/:id.json", {
id: "#id"
});
return {
getEvent: function () {
var deffered = $q.defer();
resource.get({
id: "event"
},
function (event) {
deffered.resolve(event);
},
function (status) {
deffered.reject(status);
});
return deffered.promise;
},
save: function (event) {
var deffered = $q.defer();
event.id = 999;
resource.save(event,
function (data, status, header, config) {
deffered.resolve(data);
},
function (data, status, header, config) {
deffered.reject(data);
}
);
return deffered.promise;
}
}
});
ControllerJS
eventsApp.controller('editEventCtrl', function ($scope, eventData) {
// Save Event
$scope.saveEvent = function (event, newEventForm) {
if (newEventForm.$valid) {
//alert("Event '" + event.ename + "' Saved Successfully !");
eventData.save(event)
.then(
function (response) {
console.log('Success ' + JSON.stringify(response));
},
function (response) {
console.log('Failure ' + JSON.stringify(response));
}
)
}
};
});
Please help me.

Angular Testing controller with factory

Hello I have this controller that handles login:
angular.module('fancyApp')
.controller('MainCtrl', function ($scope, $location, $http, LoginFactory) {
$scope.loginForm = function(isValid) {
if (isValid) {
var status;
LoginFactory.login($scope.person).then(function(d) {
console.log(d);
$scope.data = d;
if (d.status === 200) {
//login success
$('.loginFail').hide();
$location.path('/student');
} else {
$scope.loginFail = 'Failed to login';
$('.loginFail').show();
}
});
} else {
$scope.login_form.submitted = true;
}
};
});
And this is my LoginFactory login function:
angular.module('fancyApp')
.factory('LoginFactory', function ($http, $q) {
return {
login: function(user) {
var promise = $http.post( 'api/v1/login', user).then(function (response) {
return response;
}, function(error) {
return error;
});
return promise;
};
});
This is my beforeEach:
beforeEach(inject(function ($controller, $provide, $location, $rootScope) {
location = $location;
rootScope = $rootScope;
var testService = {
getStudents: function() {
return ['student1', 'student2'];
},
getAdmins: function() {
return ['admin1', 'admin2'];
},
login: function(person) {
console.log(testService.getStudents().indexOf(person.user));
if(testService.getStudents().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'student'};
}
else if(testService.getAdmins().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'admin'};
}
else {
return {status:401, token:'xxx', role:'student'};
}
}
};
scope = $rootScope.$new();
$provide.service('LoginService', testService);
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
And here is my test:
it('Login should succeed', inject(function($httpBackend){
spyOn(testService, 'login');
scope.person.user = 'student1';
scope.person.pass = '123456';
scope.login(true);
expect(testService.login).toHaveBeenCalledWith('student1', '123456');
}));
The error I get is:
Error: [$injector:unpr] Unknown provider: $provideProvider < $provide
I'm not sure if this is the correct way of testing this, any suggestions would be nice.
Thank you.
You can't use $provide within the inject function because the former registers providers for the latter to use. Do it like this:
describe('...', function() {
beforeEach(function() {
module(function($provide) {
$provide.service('LoginService', testService);
});
inject(function(someValue) {
//Rest of the code within the inject..........
});
});
});

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