I'm using Restangular interceptor to handle errors with status code as 412,409 etc.
But I'm not getting status in the requestInterceptor function.
I have declared the Restangular RequestInterceptor using Typescript.
In my app.ts file,
app.run(Restangular){
Restangular.setErrorInterceptor(function(response) {//code to handle error});
}
Error:
Restangular provides an option to access a full response access, probably setting up this might help. By using Restangular.setFullResponse(true) you should be able to access the status code in your interceptor.
So, I guess according to your snippet now it could look like this(since there is where you are injecting Restangular if you have any other configuration section that where the setting should go)
app.run(Restangular){
Restangular.setFullResponse(true);
Restangular.setErrorInterceptor(function(response) {//code to handle error});
}
It's important to point out that setting up this option, now the access to your responses will be sightly different for all your services unless you create something to handle the next .data behavior:
function(response){
var result = response.data;
var statusCode = result.status;
var responseData = result.myApiResponse;
}
For more information please check: https://github.com/mgonto/restangular#setfullresponse, and hope my post helps.
Related
I need to emulate some state in my developer utility, and for it I need to pass some special cookie to the http request which made via angular $http module.
Code for making http request looks simple:
if (condition){
var headers = getHeaders();
if (headers !== 'undefined'){
config['headers'] = headers;
}
}
return $http(config);
So looks like I should add some field to the this config. But I can't find any related data about this in $http docs.
I do not want to set cookie 'to the browser' becase I want to pass it only for some several requests performed asynchronously.
Is it real to nmake it with angular.js?
I’m trying to implement authentication in my angularjs app.
I’ve read some articles about doing this properly. Here is one, for instance: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
But I can’t realize how to make it respond on wrong username/password pair.
Let’s have a look at this code :
authService.login = function (credentials) {
return $http
.post('/login', credentials)
.then(function (res) {
// populate user info
}
);
};
I’ve tried to add here a second callback to “then” method and use “success”/”error” methods instead of “then” and I’ve tried to response on $http.post request with different error like 400 and 500 via status, but in any case all the errors are handled by the success method and callback.
What am I doing wrong? How to catch wrong password/username response in angular?
It was actually my own fault. My custom Intereptor simply swallowed authenticaion errors.
I'm developing web app with angular.js, I'm currently a little confused about what's the proper way to handle errors. In my app, I have used ngResource to call rest API of server. So I'll have a lot of ngResource api calls.
e.g. user resource, there're user.query( ), user.get( ) , user.save( ) ......
Do I suppose to put an error callback into all of the ngResource api calls?
Just to handle all kinds of errors: like server down or no internet access ??
I just don't think put an error callback in every ngResource api call is a good idea. That'll produce a lot of redundant code and make my code not neat .
What will you do to handle various error types?
You can use an interceptor and do whatever you want when an error occured :
var app = angular.module("myApp", []);
app.config(function ($provide, $httpProvider) {
$provide.factory('ErrorInterceptor', function ($q) {
return {
responseError: function(rejection) {
console.log(rejection);
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('ErrorInterceptor');
});
With this interceptor you can read the status code and do what you need (a perfect use case is to redirect your user to a login page if status code is 401).
Since ngResource use $http, your interceptors will also be executed when you call a resource method.
Of course, you can do more and add an interceptor before / after a request is made.
See the full documentation here : http://docs.angularjs.org/api/ng.$http
See this fiddle : http://jsfiddle.net/4Buyn/ for a working sample.
I am using AngularJS Services in my application to retrieve data from the backend, and I would like to make a loading mask, so the loading mask will start just before sending the request. but how can I know when the request ends?
For example I defined my servive as:
angular.module('myServices', ['ngResource'])
.factory('Clients', function ($resource) {
return $resource('getclients');
})
.factory('ClientsDetails', function ($resource) {
return $resource('getclient/:cltId');
})
So I use them in my controller as:
$scope.list = Clients.query();
and
$scope.datails = ClientsDetails.get({
date:$scope.selectedId
});
So the question would be, how to know when the query and get requests ends?
Edit:
As a side note in this question I've been using using angularjs 1.0.7
In AngularJS 1.2 automatic unwrapping of promises is no longer supported unless you turn on a special feature for it (and no telling for how long that will be available).
So that means if you write a line like this:
$scope.someVariable = $http.get("some url");
When you try to use someVariable in your view code (for example, "{{ someVariable }}") it won't work anymore. Instead attach functions to the promise you get back from the get() function like dawuut showed and perform your scope assignment within the success function:
$http.get("some url").then(function successFunction(result) {
$scope.someVariable = result;
console.log(result);
});
I know you probably have your $http.get() wrapped inside of a service or factory of some sort, but you've probably been passing the promise you got from using $http out of the functions on that wrapper so this applies just the same there.
My old blog post on AngularJS promises is fairly popular, it's just not yet updated with the info that you can't do direct assignment of promises to $scope anymore and expect it to work well for you: http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/
You can use promises to manage it, something like :
Clients.query().then(function (res) {
// Content loaded
console.log(res);
}, function (err) {
// Error
console.log(err);
});
Another way (much robust and 'best practice') is to make Angular intercepting your requests automatically by using interceptor (see doc here : http://docs.angularjs.org/api/ng.$http).
This can help too : Showing Spinner GIF during $http request in angular
As left in a comment by Pointy I solved my problem giving a second parameter to the get function as following:
$scope.datails = ClientsDetails.get({
date:$scope.selectedId
}, function(){
// do my stuff here
});
in AngularJs 1.2.x, the docs only provide a rejection object, how can we see the actual response object? (to see things like http status code)
edit: here's an example from the docs:
// register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
});
that example shows some unknown rejection object (no docs on what it's members are). the old (deprecated responseInterceptors allow query of the response object. (check for status=401, for example) how are you supposed to query for 401 service errors with the new interceptor functionality?
i am coding my usage of this to the point of being able to run it,
and so i set a breakpoint, and see that the "rejection" object has a .status property.
if a server doesn't exist, it will == 0
otherwise, it seems to return the http status code. (i see 404 so far)
I havent coded a real service point so i'll update this answer and/or accept it once i get that done.
update: yes, the .status field returns the http response status, and 0 if server not found. so this is the valid answer!