How to set $http.error() in angular throughout all $http calls? - javascript

How would I go about setting a function for all .error calls from the $http service wherever used.
Throughout my app I have used many $http calls wrapped in a service and would like to avoid duplication of implementing all .error methods.
e.g.
postTest: function (data) {
var url = '/test';
return $http({
method: 'POST',
url: url,
data: data
}).
success(function (data) {
return data;
}).
error(function (status) { //Avoid duplication of this throughout all $http calls.
if (status === 404) {}
return status;
});
}

you could create and interceptor to catch all the errors
so something like this
var applicationWideInterceptors = function ($q, toastrSrvc) {
return {
responseError:function(rejection) {
//do something with the rejection
if (rejection.status === 404) {
toastrSrvc.error(rejection.data);
}
return $q.reject(rejection);
}
}
};
app.factory("appWideIntercpt", ["$q", "toastrSrvc", applicationWideInterceptors]);
dont forget to add it to your config block
$httpProvider.interceptors.push("appWideIntercpt"

Related

is it possible not to execute the promise (.then ()) in the controller when there is an error in a web request?

I'm currently using a factory called http that when I invoke it, I make a web request. this receives as a parameter the url of the web request.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(data) {
oHttp.data=data.data;
},function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
function HelloCtrl($scope, http) {
http.getData('https://www.reddit.com/.json1').then(function(){
if(http.data!=undefined){
console.log(http.data)
}
})
}
I would like the promise not to be executed on the controller if the result of the web request is not satisfied or there is a problem. is there any better solution? I want to avoid doing this every time I make a web request, or do not know if it is the best way (see the if):
//I am putting "1" to the end of the url to generate an error.
http.getData('https://www.reddit.com/.json1').then(function(){
//validate that the result of the request != undefined
if(http.data!=undefined){
alert(http.data.kind)
}
})
In my real project I make n web requests using my factory http, I do not want to do this validation always. I do not know if I always have to do it or there is another solution.
this is my code:
https://plnkr.co/edit/8ZqsgcUIzLAaI9Vd2awR?p=preview
In rejection handlers it is important to re-throw the error response. Otherwise the rejected promise is converted to a successful promise:
app.factory('http', function ($http) {
var oHttp= {};
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(response) {
̶o̶H̶t̶t̶p̶.̶d̶a̶t̶a̶=̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
return response.data;
},function(response) {
alert("problem, can you trying later please?")
//IMPORTANT re-throw error
throw response;
});
}
return oHttp;
});
In the controller:
http.getData('https://www.reddit.com/.json1')
.then(function(data){
console(data)
}).catch(response) {
console.log("ERROR: ", response.status);
});
For more information, see You're Missing the Point of Promises.
In Service
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function () {
return $http({
method: 'GET',
url: 'https://www.reddit.com/.json1'
});
}
return oHttp;
});
In controller
function HelloCtrl($scope, http) {
var httpPromise = http.getData();
httpPromise.then(function(response){
console.log(response);
});
httpPromise.error(function(){
})
}
So I tried this in codepen having ripped your code out of plinkr
https://codepen.io/PocketNinjaDesign/pen/oGOeYe
The code wouldn't work at all...But I changed the function HelloCtrl to a controller and it seemed happier....?
I also set response.data to default to an empty object as well. So that way if you're populating the data in the page it will be empty if nothing arrived. You can then in some instances on the site check the length if it's really required.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.data = {};
oHttp.getData= function (url) {
var config = {
method: 'GET',
url: url
}
return $http(config).then(function(response) {
oHttp.data = response.data || {};
}, function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
app.controller('HelloCtrl', function($scope, http) {
http.getData('https://www.reddit.com/.json').then(function(){
alert(http.data.kind);
})
});

Loader not being shown on ajax request in angular js

Since I am using ajax request using $http. It takes a long time since my operation on server takes time. I need to show loader while processing request, but the loader does not show. Although my code seems correct. I tried different methods but did not work.
Index.html
<body ng-app="app">
<!-- loader, can be used on multiple pages-->
<div class="loading loader-quart" ng-show="isLoading"></div>
<!-- my logic -->
</body>
addCtrl.js
//method to get all the attributes and send to server using service
$scope.add = function () {
if ($scope.Option == 'newInstance')
$scope.singleObject.FK_Name = 'MetisEmptyTemplate';
$rootScope.isLoading = true;
var featuresList = websiteService.getUpdatedTree($scope.treeDataSource);
var formData = new Website("", $scope.singleObject.Name, $scope.singleObject.DisplayName, $scope.singleObject.Description, $scope.singleObject.State, "", $scope.singleObject.FK_Name, $scope.singleObject.Email, featuresList);
websiteService.addwebsite(formData);
$rootScope.isLoading = false;
}
websiteService.js
//service to add website
this.addwebsite = function (website) {
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
}).error(function (data, status, headers, config) {
//alert(data);
});
}
Since I am going to turn isLoading as "true" in start and then after request completes I turn isLoading "false". Where is the problem in code?
Your websiteServices code gets executed asynchronously. Which means that the above code would display the loader and then pretty much hide it again instantly.
To handle async code in the controller you must return a promise from the service and put the hiding of the spinner in a callback function using .then().
service:
this.addwebsite = function (website) {
var deferred = $q.defer();
$http({
method: 'POST',
url: $rootScope.url + 'Add',
data: JSON.stringify(website),
contentType: 'application/json'
}).success(function (data) {
alert(data);
deferred.resolve(data);
}).error(function (data, status, headers, config) {
//alert(data);
deferred.reject(data);
});
return deferred.promise
}
controller:
websiteService.addwebsite(formData).then(function(){
$rootScope.isLoading = false
});
this.insertMliveResponse = function(data){
var defer=$q.defer();
var requestURL='/mlive-portlet/rest/mliveResponseService/insertmLiveResponse';
httpRequest(requestURL,data).then(function(data){
defer.resolve(data.data);
},function(data){
defer.reject(data.data);
})
return defer.promise;
}
If you are making request then,
I think the best way to show hide loader is interceptor
In my snippet, I am using loader service to activate/deactivate loader
For Eg:
// http.config.js file
export function httpConfig($httpProvider, AuthInterceptProvider) {
'ngInject';
AuthInterceptProvider.interceptAuth(true);
// added for show loader
$httpProvider.interceptors.push(function (loaderService, $q) {
'ngInject';
return {
'request': function (config) {
loaderService.switchLoaderModeOn();
return config;
},
'requestError': function (rejection) {
loaderService.switchLoaderModeOff();
return $q.reject(rejection);
},
'response': function (response) {
loaderService.switchLoaderModeOff();
return response;
},
'responseError': function (rejection) {
loaderService.switchLoaderModeOff();
return $q.reject(rejection);
}
};
});
}
// and in your module.js file
import {httpConfig} from './config/http.config';
.config(httpConfig)

Data object variable in angular service to update via ajax call

Use Case:
I want to create a service in angular which will return me a data object which is a variable inside service, which gets updated once via ajax call.
For first time till data is not received via ajax, it will return {}. Once data is received it will return that data always.
Issue:
The data is properly received in ajax. The structure of data received is an object. I have checked it by logging in console. But next time when this service is called it is again calling ajax as variable inside service is not getting updated.
Can anyone suggest why is this happening and what would be the idle way to achieve above ?
Code:
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS) {
this.tagsData = {};
this.getTagsData = function (cacheMode) {
if (JSON.stringify(this.tagsData) != "{}") {
console.log("returning from cache");
return this.tagsData;
}
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
this.tagsData = data["data"];
}
return this.tagsData;
}).error(
function (data, status, headers, config) {
return {};
});
};
});
You should not use this in your function. The this keyword is function scoped. You're not updating the same variable in your callback and in your first condition.
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS) {
var tagsData = {};
this.getTagsData = function (cacheMode) {
if (JSON.stringify(tagsData) != "{}") {
console.log("returning from cache");
return tagsData;
}
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
tagsData = data["data"];
}
return tagsData;
}).error(
function (data, status, headers, config) {
return {};
});
};
});
One more thing, you must use promise rather than returning your datas. Check the documentation about $q here.
The right way should be :
angular.module('myapp', []).service('TagService', function ($http, CONSTANTS, $q) {
var tagsData = {};
this.getTagsData = function (cacheMode) {
var defer = $q.defer();
if (JSON.stringify(tagsData) != "{}") {
console.log("returning from cache");
defer.resolve(tagsData);
}else{
$http({
method: 'GET',
url: CONSTANTS['base_url_s'] + 'api/v1/get_all_tags_data/',
params: {'params': JSON.stringify({})}
}).success(
function (data, status, headers, config) {
if (data && data["success"] && data["success"] == true) {
tagsData = data["data"];
}
return defer.resolve(tagsData);
}).error(
function (data, status, headers, config) {
return defer.reject({});
});
};
}
return defer.promise;
});
And then you should call:
TagService.getTagsData().then(function(yourTags){
// yourTags contains your data
});

How do you deal with asynchronous return from $http.post in angularJS?

Stuck with a simple basic login problem here. My AuthService factory has following code inside of it (2 relevant functions and a local variable):
var username = '';
function login(uname, upwd, utype) {
// create a new instance of deferred
var deferred = $q.defer();
$http({
method: 'POST',
url: '/root',
headers: {
'Content-Type': 'application/json'
},
data: {
username: uname,
password: upwd,
type: utype
}
}).success(function(data, status, headers, config) {
if (status === 200) {
user = true;
username = data.username;
usertype = data.usertype;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
.error(function(data, status, headers, config) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function getusername() {
return username;
}
My controller looks like this:
angular.module('smApp').controller('rootloginController', ['$scope', '$location', 'notificationFactory', 'AuthService',
function($scope, $location, notificationFactory, AuthService) {
$scope.submit = function() {
AuthService.login($scope.rEmail, $scope.rootPassword, 'root')
if (AuthService.isLoggedIn()) {
$location.url('/dashboard');
notificationFactory.success('Logged in as ' + rootEmail);
} else {
//ngNotifier.notifyError($scope.rEmail);
notificationFactory.error('Invalid username & password combination');
}
};
};
}]);
I am calling my getusername() in the if statementright after login() and since login has $http post it's asynchronous and I think im hitting a wall here.
So my main problem here is the first click always gives me error message and the second clicks logs me in. I am assuming this has to do with the promise not being fulfilled right away and taking some time to execute. I was wondering if there was anyway around this? I really dont have any other code to execute beside wait since this is a login page and using a timeout doesnt seem like the proper way to do it.
In this case you need to use the Promise API. Calls to the server made via the $http service return a promise, which allow binding of .success and .error methods.
The .then method may be used as a shorthand for both .success and .error. It accepts two functions that it executes in success and error scenarios respectively. Returning a promise in those functions allows chaining calls to the server.
In most cases, this should suffice:
// In service
login: function () {
return $http.post('your:url').then( // `then` here is optional, but possible
function () {}, // update service values without having to involve the controller (and/or transform the response object)
function () {} // throw error log mesages
)
}
// In controller
$scope.submit = function () {
AuthService.login().then(
function () {
// success logic: redirect, assign scope variables, etc
},
function () {
// error logic: allow retry
}
);
}
You have to call AuthService.isLoggedIn() after the login request has been completed. For this, first return the promise of the deferred object you created.
function login(uname, upwd, utype) {
// create a new instance of deferred
var deferred = $q.defer();
$http({
method: 'POST',
...
return deferred.promise;
}
Now, you can wait for the request to complete.
AuthService.login($scope.rEmail, $scope.rootPassword, 'root').finally(function() {
if (AuthService.isLoggedIn()) {
$location.url('/dashboard');
notificationFactory.success('Logged in as ' + rootEmail);
} else {
//ngNotifier.notifyError($scope.rEmail);
notificationFactory.error('Invalid username & password combination');
}
});

AngularJS: Call a particular function before any partial page controllers

I want to call a particular function: GetSession() at the beginning of my application load. This function makes a $http call and get a session token: GlobalSessionToken from the server. This session token is then used in other controllers logic and fetch data from the server. I have call this GetSession()in main controller: MasterController in $routeChangeStart event but as its an asynchronous call, my code moves ahead to CustomerController before the $http response.
Here is my code:
var GlobalSessionToken = ''; //will get from server later
//Define an angular module for our app
var myApp = angular.module('myApp', ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/customer', {
templateUrl: 'partials/customer.html',
controller: 'CustomerController',
resolve: {
loadData: function($q){
return LoadData2($q,'home');
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
//controllers start here and are defined in their each JS file
var controllers = {};
//only master controller is defined in app.js, rest are in separate js files
controllers.MasterController = function($rootScope, $http){
$rootScope.$on('$routeChangeStart', function(){
if(GlobalSessionToken == ''){
GetSession();
}
console.log('START');
$rootScope.loadingView = true;
});
$rootScope.$on('$routeChangeError', function(){
console.log('ERROR');
$rootScope.loadingView = false;
});
};
controllers.CustomerController = function ($scope) {
if(GlobalSessionToken != ''){
//do something
}
}
//adding the controllers to myApp angularjs app
myApp.controller(controllers);
//controllers end here
function GetSession(){
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
}).error(function (data, status, headers, config) {
console.log(data);
});
}
And my HTML has following sections:
<body ng-app="myApp" ng-controller="MasterController">
<!--Placeholder for views-->
<div ng-view="">
</div>
</body>
How can I make sure this GetSession() is always called at the very beginning of my application start and before any other controller calls and also called only once.
EDIT: This is how I added run method as per Maxim's answer. Still need to figure out a way to wait till $http call returns before going ahead with controllers.
//Some initializing code before Angular invokes controllers
myApp.run(['$rootScope','$http', '$q', function($rootScope, $http, $q) {
return GetSession($http, $q);
}]);
function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
}
Even though some of the solutions here are perfectly valid, resolve property of the routes definition is the way to go, in my opinion. Writing your app logic inside session.then in every controller is a bit too much , we're used such approach too in one of the projects and I didn't work so well.
The most effective way is to delay controller's instantiation with resolve, as it's a built-in solution. The only problem is that you have to add resolve property with similar code for every route definition, which leads to code duplication.
To solve this problem, you can modify your route definition objects in a helper function like this:
function withSession(routeConfig) {
routeConfig.resolve = routeConfig.resolve || {};
routeConfig.resolve.session = ['getSessionPromise', function(getSessionPromise) {
return getSessionPromise();
}]
return routeConfig;
}
And then, where define your routes like this:
$routeProvider.when('/example', withSession({
templateUrl: 'views/example.html',
controller: 'ExampleCtrl'
}));
This is one of the many solutions I've tried and liked the most since it's clean and DRY.
You can't postpone the initialisation of controllers.
You may put your controller code inside a Session promise callback:
myApp.factory( 'session', function GetSession($http, $q){
var defer = $q.defer();
$http({
url: GetSessionTokenWebMethod,
method: "POST",
data: "{}",
headers: { 'Content-Type': 'application/json' }
}).success(function (data, status, headers, config) {
GlobalSessionToken = data;
defer.resolve('done');
}).error(function (data, status, headers, config) {
console.log(data);
defer.reject();
});
return defer.promise;
} );
myApp.controller( 'ctrl', function($scope,session) {
session.then( function() {
//$scope.whatever ...
} );
} );
Alternative: If you don't want to use such callbacks, you could have your session request synchronous, but that would be a terrible thing to do.
You have not provided any details related to GetSession. For scenarios like this you should use the resolve property while defining your routes in $routeProvider. I see you are using resolve already.
What you can do now is to wrap the GlobalSessionToken into a Angular service like GlobalSessionTokenServiceand call it in the resolve to get the token before the route loads. Like
resolve: {
loadData: function($q){
return LoadData2($q,'home');
},
GlobalSessionToken: function(GlobalSessionTokenService) {
return GlobalSessionTokenService.getToken() //This should return promise
}
}
This can then be injected in your controller with
controllers.MasterController = function($rootScope, $http,GlobalSessionToken){

Categories

Resources