Does angularjs have something similar to jQuery's ajaxSetup? - angularjs

I've browsed through the documentation but couldn't find anything mentioning this. I'm using Angular's $http service and want to run code before every ajax event, and after every ajax event (to display a loading message while waiting for the server to respond).
I have jQuery included and tried doing:
$(document).ready(function() {
$('body').ajaxSend(function(event, jqXHR) {
console.log('in jquery send');
}) ;
});
But couldn't get the message logged to the console. Any help is appreciated.

Please check out the docs on $http service: http://docs.angularjs.org/api/ng.$http
You will see that there are two options that you can use:
httpInterceptor (see Response interceptors section in the docs) - it allows you to wrap every response and do whatever you want before it completes the request. It uses promises so it's really easy to even do some async stuff after each request.
request/response transformations (see Transforming Requests and Responses) - it allows you to process every request and response that goes through $http - so that would be my choice as it allows you to hook before and after the request.

Related

How can I access the $location service without using it in the .controller()?

I am new to Angular. I am trying to change the location of the URL only when a jquery ajax response is successful. But the issue is the only way I know how to use the $location service is through the controller.
I only want to run the $location.path('/'); when an ajax response is complete.
This is what I have for now..
app.controller("myCtrl",function($scope,$location){
$location.path('/basemenu');
})
But I can't run it only on success because it will give me an error, and I can't run on the page load either.
Does anyone know how I can do this?
$location service is a wrapper built around window.location.
in browser's context window object is exposed to all js snippet ( controller,service,factory etc..)
use
window.location.pathname = '<new path>';

How to handle the response from PayPal In-Context in AngularJS instead of NodeJS

I'm having trouble getting a response from server side NodeJS code after checking out using PayPal In-Context via the paypal-rest-sdk.
I have a PayPal form defined in html, and purposefully did not define the action. I only defined the id and method (get). In my Angular code, I define the action when the PayPal button is clicked:
var payPalForm = document.getElementById('payPalForm');
payPalForm.addEventListener("click", function(e) {
payPalForm.setAttribute('action', "https://10.0.0.25:8001/checkout/" +
$scope.user._id + "/" + $scope.viewEvent._id.valueOf() + "/" +
$scope.viewEvent.eventName + "/" + $scope.viewEvent.price);
});
By doing this, I am able to successfully checkout via PayPal In-Context.
In my NodeJS code, after successful checkout, instead of return res.end(); if successful or res.sendStatus(400, 'bad paypal payment'); if failure, I would like to pass the status back to the Angular, and handle it there.
To reiterate: I do not want to define the post PayPal In-Context route in NodeJS, I would like to do it in Angular.
I need to do this being I am using Onsen UI, and am using a splitter to navigate between pages.
Has anyone successfully done this?
UPDATE AFTER ATTEMPTING THE FIRST ANSWER
I have tried this before, but after attempting to implement Ilia Sky's Answer, the result is the PayPal In-Context checkout does not execute correctly. The script runs correctly (as determined by output in the terminal), but the In-Context window loads with "?" as a parameter and then immediately closes itself. Here are screenshots on how I updated my code. The commented out code is what I had when I was able to successfully checkout, but unable to redirect properly:
I think this is an issue with PayPal, and I'm not sure how to solve it.
This is why I'm wondering if I can listen for a redirect in Angular, and then load a different page when a certain redirect is identified.
I tried this in my Angular controllers, but it only ever executed when the initial page loaded:
I may be wrong, but from what I understand what you want to do is:
Send data to the server (to https://10.0.0.25:8001/checkout/...)
Do something on the server and give a response (res.send etc)
Handle the response on the client
Right?
To do this the easiest solution would be just to send an ajax request to the server and then handle the response.
This means instead of changing the action attribute you can directly make the request via js. With angular that would be done using the $http service.
$http.post('https://10.0...').then(successCallback, errorCallback);
And in success|errorCallback you can do whatever you want such as load a page in the splitter or whatever you want :)
To change what happens when you try to submit the form you can check out ng-submit.
And to get $http you can just add it to your list of arguments for your controller.
Example
app.controller('ExampleController', function($scope, $http) {
$scope.submit = function() {
$http.post('your/long/url').then(function(response) {
mySplitter.content.load('success-page.html');
}, function(response) {
mySplitter.content.load('error-page.html');
});
};
}]);
<form ng-submit="submit()" ng-controller="ExampleController">
...
</form>
I encourage everyone to check out this link.
One of the PayPal developers has posted a sample Kraken with Angular example of the PayPal In-Context Checkout.

Load YouTube Iframe API using XHR (AngularJS' $http) and CORS

I want to load the YouTube Iframe API ( https://www.youtube.com/iframe_api ) using AngularJS' $http, but it seems that YouTube doesn't allow CORS requests.
The reason I want to load this API using XHR is that I have a fairly complex logic for API loading in my app, and I want to test it using $httpBackend. And if I load the script using a tag created from JS, I can't find any way of mocking it, and also it will actually execute the request each time I run the tests, which is not cool.
My other option is to create a local proxy, but I would like to avoid that at the current moment.
So, does anyone know any way of loading the YouTube Iframe API with XHR? Maybe setting an origin parameter to the request or something. Or maybe it already works but I'm missing something.

AngularJS bind function to ajax ($http) start/end/error

I would like to attach a function that gets executed whenever Angular is making an $http request. What I'm trying to do is essentially show a loading spinner whenever any Ajax Requests are being made by any App. In jQuery I have done this in the past by:
$(document).ready(function(){
$("#spinner").bind("ajaxSend", function() {
$(this).show();
}).bind("ajaxStop", function() {
$(this).hide();
}).bind("ajaxError", function() {
$(this).hide();
});
});
Any insight into how I can attach a function that shows and hides a loading div whenever any controller throughout the application performs an Ajax Request?
Maybe there is a better way (directives?)
Thanks!
Alessandro Ferrucci
the only thing that monitors all traffic in the app are the httpInterceptors youll have to write an inteceptor as a service that shows your div, when a request is detected and hides it when a response is detected.
interceptor are creaeted as services and passed to the $HttpProvider at config time.
you can read about it here
https://docs.angularjs.org/api/ng/service/$http

AngularJS $http not sending GET request

In an Angular JS app I'm working on, I am using a service to periodically (in a $timeout) make a GET request to a URL in my API (both the Angular app and the API are being served from port 5000 on localhost).
For some reason, it appears that $http is not actually sending the GET. For each $http.get(), the .error() is called with empty data and a status of 0. When I check in my server log (I'm running a Ruby on Rails backend with the Unicorn gem for my server), it appears that the server never receives the request from Angular.
Here's the function in my service:
updateUserStatus = () ->
$http.get('/api/v1/status').success (statusData) ->
# update the variable and notify the observers
this.userStatus = statusData
notifyObservers()
startStatusTimeout()
.error (error, status) ->
# if there's an error, log it
console.log 'error:'
console.log error
console.log status
startStatusTimeout()
What's really odd is that it only happens sometimes. When it stops working, I can change the URL in the $http.get() to '/api/v1/status.json', and it works. For a while. Then I switch it back and it works again, for a while... obviously there is some greater issue at play.
I've been racking my brain for a few days now, and I've seen a bunch of similar issues on SO, but they all seem to be solved with implementing CORS in Angular, which I don't think is applicable to my situation because it's all coming from localhost:5000. Am I wrong? What's going on?
For reference, I'm using Angular version 1.0.7.
I had the same problem.
Check your code to see whether this happens after events that are fired from the DOM and are unknown to Angular.
If so, you need to add $scope.$apply(); after the get request in order to make it happen.
I'm fairly new to Angular so I'm not sure this is the best practice for using Angular, but it did work in my case.
See this similar question for a better explanation.

Resources