Need to call AngularJS function on every ajax request - angularjs

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

Related

Circular dependency angularjs

can anyone tell me where is the circular dependency in the following code?
var homeApp = angular.module("homeApp",['ngAnimate', 'ui.bootstrap']);
'use strict';
homeApp.factory('AdminDashboardService', ['$http', '$q', function($http, $q){
return {
'response': function(response) {
// do something on success
console.log("Yes Command comes here");
return response;
},
getAllHolidays: function(monthYearArrayForHolidayList) {
console.log("For full list of holidays list length: "+monthYearArrayForHolidayList.length);
var isMonthly="no";
return $http.get('/tasktrac/holiday/getHoliday/isMonthly/'+isMonthly+'/'+monthYearArrayForHolidayList)
.then(
function(response){
return response.data;
},
function(errResponse){
//console.error('Error while fetching holiday');
return $q.reject(errResponse);
}
);
},
}]);
homeApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('AdminDashboardService');
}]);
I am stuck at this point please do me a favour in resolving this issue.
This is the Error I got on the browser
Please click here to see error
Thank you..!!
A $http interceptor could not declare $http as a dependency!
Inject $injector:
homeApp.factory('AdminDashboardService', ['$injector', '$q', function($injector, $q){
return {
'response': function(response) {
// do something on success
console.log("Yes Command comes here");
return response;
},
getAllHolidays: function(monthYearArrayForHolidayList) {
console.log("For full list of holidays list length: "+monthYearArrayForHolidayList.length);
var isMonthly="no";
return $injector.get("$http").get('/tasktrac/holiday/getHoliday/isMonthly/'+isMonthly+'/'+monthYearArrayForHolidayList)
.then(
function(response){
return response.data;
},
function(errResponse){
//console.error('Error while fetching holiday');
return $q.reject(errResponse);
}
);
},
}]);

MVC and Angularjs : promise does not waiting data

i'm newby in angularjs i researched on the internet but i couldn't find any suitable solution for my problem. I made an http call to get some data from controller. The controller side is okay. But the client-side, promise does not waiting data. Here codes that I wrote ;
//service code
angular.module("myApp").service('$myService', function ($http, $q) {
this.getDataArray = function () {
var deferred = $q.defer();
$http.get('../Home/GetDataArray')
.success(function success(response) {
deferred.resolve(response);
})
.error(function () {
console.log("error getting data array");
deferred.reject();
});
return deferred.promise;
};
}
// controller-code
angular.module("myApp").controller('dataController', function ($scope, $http, $myService) {
$scope.getDataFromService = function () {
$myService.getDataArray().then(function (response) {
$scope.dataArray = response.data;
});
};
});
}
When i call the getDataFromService method at first $scope.dataArray is empty, but the second call, $scope.dataArray is filled with data. Where is the problem? Thanks for helps.
Not an angular expert myself. This is just how I did it when I ran into the same problem. Try this:
Controller:
angular.module("myApp").controller('dataController',[ '$scope', 'Service1', '$http', function ($scope, Service1, $http) {
var deferred = Service1.getDataArray().$promise;
return deferred.then(function successCallback(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.dataArray = response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}])
and service:
var service = angular.module("myApp").service('myService', ['ngResource']);
myService.factory('Service1', ['$resource',
function ($resource) {
return $resource('../Home/GetDataArray', {}, {
get: { method: 'GET', isArray: true },
});
}])
The idea is that your service isn't the one that should wait for a return, your controller is. So you should wait for the promise in your controller not your service. In my example I am using factories because, well, that's how I got around it in my project, you can try and implement this directly if you don't want to use a factory.

Can't Access Factory Function (Undefined is not a function)

I'm trying to call the getStuff function from my controller, but I get an error in the console saying that "undefined is not a function". I'm trying to return JSON from the GET and then store it in a $scope variable.
app.factory('UserInfo', function($http) {
var user = [];
return{
getStuff: function(){
user.push($http.get('api/users'));
return user;
},
testPost: function(){
return $http.post('api/users');
}
};
});
The factory is hooked up to the controller as follows
.controller('TwitterController', function($scope, $q, $interval, UserInfo) {
and here's the $scope function I'm using to call the factory function
$scope.datapls = function() {
UserInfo.getStuff().success(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}
Thanks! I appreciate the help.
You're error refers to the .success() function - it doesn't exist.
It looks like you're trying to use promises. If that's the case, then you need to return the promise itself from your service.
Something like this (not tested, but an idea). You want to use the $q in your service, not your contorller.
The examples in the $q on AngularJS docs section are great.
So by doing this, your controller doesn't have to wait around for the data. As soon as it's resolved
app.service('UserInfo', function($http, $q) {
this.getStuff = function(){
var deferred = $q.defer();
$http.get('api/users').success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
}
}
);
And in your controller you can do this:
UserInfo.getStuff().then(function(dataFromService){
// dataFromService is used in here..
$scope.loaduser.push(dataFromService);
}, function(error) {
// the error will come in via here
});
According to the docs, $http in itself returns a promise, you can change your factory function in order to achieve what you trying to do:
app.factory('UserInfo', function($http) {
return{
getStuff: function(){
return $http.get('api/users'));
},
testPost: function(){
return $http.post('api/users');
}
};
});
and in the controller:
$scope.datapls = function() {
UserInfo.getStuff().then(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}

AngularJS Interceptor to Redirect

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")
}
}
}
}
]);

AngularJS - Redirect to Login page and Persistence of Session ID

I am looking for a way to do these two things, first I want to redirect the user to a login page if no SessionID is found and second I would like to hear your opinion about persisting session ID in memory only (no cookies).
The solution I came up with for the redirect is:
1 - Create a service called OAuth that will check if SessionID exists and if not, redirects to login page, the service is also responsible for the login and logout methods.
app.factory('OAuth', ['$http', function ($http) {
var _SessionID = '';
return {
login: function () {
//Do login ans store sessionID in var _SessionID
},
logout: function () {
//Do logout
},
isLoggedIn: function () {
if(_SessionID) {
return true;
}
//redirect to login page if false
}
};
}]);
2 - Inject the new OAuth service in each controller and check if user isLoggedIn
app.controller('myCtrl', ['$scope', 'OAuth', function ($scope, OAuth) {
//check if user is logged
OAuth.isLoggedIn();
}]);
Questions:
1 - The isLoggedIn() method will be called in all controllers, so I wonder if there is a way to do this without having to inject the service and call it in each controller.
2 - Instead of having a cookie to store the sessionID I want to save it in OAuth's _SessionID variable and for each request send it to the server. Is this a viable/secure approach? Can you give me some ideas for that?
Thanks!
I use a similar strategy (intercepting 401 responses from the server). You can check out the full example here : https://github.com/Khelldar/Angular-Express-Train-Seed
It uses node and mobgodb on the backend for session store and a trimmed down http interceptor on the client that doens't retry requests like the one Dan linked above:
var interceptor = ['$q', '$location', '$rootScope', function ($q, $location, $rootScope) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
$location.path('/login');
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
I would start here, Witold has created this cool interceptor that works off of http responses. I use it and its been really helpful.
In my case, I used
interceptor with $httpProvider
config
and $window dependency, as $location just appended the path to the existing url. What happened was like "http://www.tnote.me/#/api/auth", and it should have bene like "http://www.tnote.me/auth"
The code snippet is like this.
noteApp = angular.module('noteApp', ['ngRoute', 'ngCookies'])
.factory('authInterceptor', ['$rootScope', '$q', '$cookies', '$window',
function($rootScope, $q, $cookies, $window) {
return {
request: function (req) {
req.headers = req.headers || {};
if ($cookies.token) {
req.headers.Authorization = 'Bearer ' + $cookies.token;
}
return req;
},
responseError: function (rejection) {
if (rejection.status == 401) {
$window.location = '/auth';
}
return $q.reject(rejection);
}
}
}])
.config(['$routeProvider', '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}
])
this will work. It works fine 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);
});

Resources