can we resolve any deferred with any response in angularjs - angularjs

I cant understand, certain things in this code http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
This code, this trying to resend same request(the one user requests before logging in) after the user logs in.
My question
Inside the retry function, they are resloving a deffered with the
response of a request that is sent after the user logs in. The
response and the deffered are no way related to each other. Why they
should do this?
-
function retry(req) {
$http(req.config).then(function(response) {
req.deferred.resolve(response);
});
}
Please have a look at the code in the above url for understanding how the retry method works.

You can resolve a promise with whatever you want. In this case, a promise was returned to the application when the 401 status code/error was first encountered. Now, after the loginConfirmed event, the request is sent again and the response is used to resolve that promise.

Related

AngualrJS - How to manage usability with multiple http error messages?

I am writing an Angular 1.5.3 app. On my main 'home' page controller I call 2 different endpoints with $http. The two endpoints are not related to each other and have separate data etc. One problem I am having is if both of those endpoints have an error then my user is going to see 2 error messages. The messages may or may not be the same (e.g. sometimes no internet connection).
FirstService.request()
.then(handleFSSuccess)
.catch(handleError);
SecondService.request()
.then(handleSSSuccess)
.catch(handleError)
function handleError(error) {
ErrorService.showErrorBanner(error);
}
I cannot use the $q.all feature or promise chaining because even if the first promise fails I want the second to continue.
I am not sure how I can manage to run all promises regardless if they one or all fail, and only show one error banner. If I only show one error banner, then the other error messages may not be shown (prevent more than one error banner from being shown).
It's better for usability if only one is shown.
FirstService.request() and SecondService.request() both return Promise and you resolve it with then/catch.
I would wrap it with new Promise that will resolve them even if failure will happen. For example:
var deferred = $q.defer();
FirstService.request().then(function(_response){
deferred.resolve(_response.data);
}).catch(function(error){
deferred.resolve({error:error}); // here we do not reject but pass error to resolve
});
return deferred.promise;
So now you can use $q.all and you will get only resolving data, or object or error object.
In one place you can filter data by error key (because you get [res1, res2])
Hope it will help you

Only status 200 is good anything else is an error in angular $http?

Quick question:
Angular $http returns a promise. The promise can be a success, resolved object (status 200) or an error, reject object (status 404). Does that mean that anything that is not a status 200 response IN angular $http will be rejected and sent to the error part of the promise? Example: 404,304,401, 500, etc.
Anything that begins with a 2xx is a successful response:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Yes by default. However, you can change that behaviour using interceptors, where you can choose what kind of promise execution to return, and that will modify the pipe to be executed in the original call.
More info about interceptors

AngularJs $http get not working 1st time but does on subsequent invocations

All:
I have an Iframe tag on a simple HTML page and inside this Iframe tag is a HTML form - lets call it a widget. Its a form where the user can enter search criteria and click on a button to obtain the search results. I have decided to use Angularjs to make the necessary DB calls to a REST service that returns the search results back to the widget for display.
In testing this I enter a value in a textbox on the widget, that value being a value that I know exists in a particular table I'm testing against.
Here is my $http get call:
$http
.get('http://localhost/XXXXService/folder/getfolders/' +
$scope.formData.srchterm **==>** mapped to search textbox
).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
//$scope.formData = response;
//$scope.nrdFolderDataArray = response;
console.log('Success retrieving data.');
console.log(response.length);
console.log('response:');
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('Error occurred retrieving data.');
console.log(response.status);
console.log('returned data count:');
console.log(response.size);
console.log('response:');
console.log(response);
});
This call is inside a function called "submitForm" that is mapped to the widget with a "ng-submit="submitForm()" attribute on the submit button. And yes there are several log statements so I can try and figure out what is going on here. And what is happening is this: after entering a value in the textbox, THE FIRST TIME the search button is clicked the .get command does not work. I does not make the call to the REST service. I know this because I wrote the REST service and made sure I put in plenty of log statements while doing so and there are no log statements in the log file from the REST service. Instead the errorCallback block runs and I see all those log statements in the console. The "response" (object?) after THE FIRST call looks like this:
Object {data: null, status: 0, config: Object, statusText: ""} Method = GET Status = (canceled) type xhr
Further, in FF there is no response data to view in the Net tab of Firebug upon THE FIRST call, but there is response data to view in all subsequent calls.
So, interestingly enough each subsequent invocation of that $http.get call works! I see log statements in the log file from the REST service method and the successCallback block runs and I can see my data via those console.log messages.
Also, if I were to change the search value in the text box, which would then be THE FIRST TIME we would be searching for data for that new key, once again, the call does not work, but does work on subsequent clicks on the "search" button for that new key value.
I really am not sure if I have a CORS issue here since, other than THE FIRST calls each subsequent $http.get call works like a champ. Its just that very first call or first call after the search key has changed that the $http.get does not want to work.
I have tried setting headers in the .get call and I have tried using
#CrossOrigin(origins = "http://localhost/7001") as per
https://spring.io/guides/gs/rest-service-cors/ but I continue to have this issue on the first time invoking this .get call.
I've been dealing with this issue for way too many hours now and would sure appreciate some input as to why this is happening.
I'm sorry for being verbose here. I wanted to explain my issue thoroughly.
Please help.
Thank you
-g

How do I get http response in Restangular .then() function from Laravel Request validation

Okay, I'm using Restangular and Laravel 5.1, and I need to be able to handle failed form validation. One way would be to do it on the front end with Angular, but I'd also like to be able to handle it server side.
Currently, the request reaches my form request, and then the form request returns
{"users":["The users field is required."]}
In my Angular controller, I have the following:
Factory.update(var1, var2).then(function(results) {
console.log("results");
});
This doesn't return anything because it's never reaching that point. Laravel kicks it out before then.
Thoughts?
I don't know Laravel, but I know how HTTP should work.
Seems like Laravel is sending back an HTTP status code for error (anything above 400 is an error).
Restangular detects this status code, and then it'll reject that promise, instead of resolving it -- that's why your console.log call is never reached.
You should do the following instead:
Factory.update(var1, var2).then(function(results) {
console.log("results");
}, function(error) {
console.log("oh you got errorz!");
});

handling $http.get and $http.post errors in Angularjs

Folks,
I am using $http.get and $http.post all over my code. I am kind of lost as to how to handle errors that occur during these calls in a global fashion.
Currently I have .success(doSomething).error(doSomething) on every call.
I would like to change this and instead simply display the error on top of my page.
I read about using interceptors with myapp.something. But I absolutely do not understand how to implement this.
Kindly assist
Response interceptors are attached during the config phase of an angularjs app. You can use them to globally respond to any $http request. Be aware, template files also use $http request, so you may wish to filter some requests in your interceptor to only the ones you wish to respond to.
A good understanding of the promises pattern is needed to successfully use response interceptors.
Heres an example of how they are used:
angular.module('services')
.config(function($httpProvider){
//Here we're adding our interceptor.
$httpProvider.responseInterceptors.push('globalInterceptor');
})
//Here we define our interceptor
.factory('globalInterceptor', function($q){
//When the interceptor runs, it is passed a promise object
return function(promise){
//In an interceptor, we return another promise created by the .then function.
return promise.then(function(response){
//Do your code here if the response was successful
//Always be sure to return a response for your application code to react to as well
return response;
}, function(response){
//Do your error handling code here if the response was unsuccessful
//Be sure to return a reject if you cannot recover from the error somehow.
//This way, the consumer of the $http request will know its an error as well
return $q.reject(response);
});
}
});

Resources