How to call Square API method asynchronously - angularjs

How to call paymentForm.requestCardNonce() method asynchronous
I am integrating square payment gateway in AngularJs, Now I have situation where I have to call paymentForm.requestCardNonce() and this method calls web service in background. Now I have to wait for background call than I can proceed with furthered process. So how can i handle callback from paymentForm.requestCardNonce() method which is provided by Square Payment Gateway https://docs.connect.squareup.com/payments/sqpaymentform/setup
Initialising code sample
var paymentForm = new SqPaymentForm({
applicationId: "sandbox-xxx-xxxxxxxxxxxx",
inputClass: 'sq-input',
callbacks: {
cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact) {
// I am receiving response of web service Here
}
}
}
How can I get success response in my custom function by calling method in it ?(Note - its working and calling a method also but i have to do next steps based on response from web service)
addCard = function () {
paymentForm.requestCardNonce();
// Till this function executes I need to wait here. how can I write promise here ?
}
Refrence LInks
https://docs.connect.squareup.com/payments/sqpaymentform/how-it-works
https://github.com/square/connect-api-examples/tree/master/templates/web-ui/payment-form/basic

For posterity, pulling from the comments.
requestCardNonce is asynchronous, and when it completes it will call cardNonceResponseReceived, so if you’re wanting to call a function after it’s finished, you should place it in cardNonceResponseReceived.

Related

I am not able to set the state of locg variable from the Google api. I need to fetch multiple location latitude and longitude from the Google API

state={locg:''}
componentDidMount(){
fetch('https://maps.googleapis.com/maps/api/geocode/json?address=TajMehal&key=xxxx').then(
response=>response.json()).then
(json=>this.setState({locg:json}));
console.log('Locations from Google wdw',this.state.locg)
}
I need to create array of latitude and longitude.But for above code itself not working for hardcoded area.locg is null
The reason why you are not seeing the result on the console is because the fetch method is asynchronous. Meaning, your console log gets executed first even though it is at the end because the fetch method takes more time to finish. And since it is asynchronous, console log does not have to wait for the fetch to finish executing.
So to address this, you must use async/await. The word async before a function means one simple thing: a function always returns a promise. And the keyword await makes JavaScript wait until that promise (fetch method) settles and returns its result. This is how it should look like:
async componentDidMount() {
await fetch('https://maps.googleapis.com/maps/api/geocode/json?address=TajMehal&key=YOUR_API_KEY')
.then(response=>response.json())
.then(json=>{
this.setState({locg:json});
console.log('Locations from Google wdw',this.state.locg);
});
console.log(this.state.locg)
}
Here is a working sample for your reference: https://stackblitz.com/edit/react-async-await-63982740

Getting data from database leading to endless http calls

I have one problem. Once I am trying to extract data from database I am getting endless http requests for some reason, which crushing my app. How can I avoid this?
readData() {
this.dataService.getData()
.subscribe(resp => {
this.data = resp;
console.log(resp);
});
}
Check if the readData is invoked during any of these events:
ngOnChanges
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked
These lifecycle hooks may be invoked multiple times during the life of a component, and can cause multiple http calls to the backend in your case.

Can i call a method call before executing my Rest API which is coming from Angular

Can i call a method before executing my Rest API which are coming from Angular I am making a post rest call (predefined API from activiti) from angular and i need to call a method before executing the rest API based on the method response i have to decide either i have to call the API or not .Can i use spring AOP? please provide your suggestions and give me any reference links so that i can go head with the implementation
[POST] http://localhost:8080/myapp/test
before this rest call i have to call a method based on the response i have to decide whether i have to call api or not[some how i traps my request and then navigate to the api]
Continuing from the comments, #Narendra, you dont have to modify your controller, what I meant is create a aspect like this
#Pointcut("#annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void requestMapping() {}
#Pointcut("within(de.some.package.controller.*) || within(de.some.package.aspect.*)")
public void myController() {}
#Around("requestMapping() && myController()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
//This will be called before and after any method in the package controller or any method with #RequestMapping annotaion is called
Object result= joinPoint.proceed();
}
This is around advice, which give you more control over the method call. You can also use #Before.
This is done from Java Annotations. I am sure you can do the same from xml as well. Here are a few examples.
http://howtodoinjava.com/spring/spring-aop/aspectj-before-advice-example/
https://www.mkyong.com/spring/spring-aop-examples-advice/

Don't execute a $resource request in angular when there is already a request running

I use a interval of 10 seconds for sending a request to get the most recent data:
var pollInterval = 10000;
var poll;
poll= $interval(function()
{
getNewestData();//$resource factory to get server data
}, pollInterval );
This works fine voor 99% of the time, but if the internet speed is really slow(I have actually experienced this), It will send the next request before the current is finished. Is there a way to just skip the current interval request if the previous one is still busy? Obsiously I could just use booleans to keep the state of the request, but I wonder if there is a better(native to angular) way of doing this?
Use the $resolved property of the Resource object to check if the previous operation is done.
From the Docs:
The Resource instances and collections have these additional properties:
$promise: the promise of the original server interaction that created this instance or collection.
$resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.
$cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.
-- AngularJS ngResource $resource API Reference.
How about making the request, then waiting for that to complete and then wait 10 seconds before making the same request again? Something along this line:
var pollInterval = 10000;
var getNewestData = function () {
// returns data in promise using $http, $resource or some other way
};
var getNewestDataContinuously = function () {
getNewestData().then(function (data) {
// do something with the data
$timeout(function () {
getNewestDataContinuously();
}, pollInterval);
});
};
getNewestData is the function that actually makes the request and returns the data in a promise.
And once data is fetched, a $timeout is started with timer as 10 seconds which then repeats the process.

Can I create an $http request and not submitting it (yet)?

I have a generic component in my system that deals with submitting HTTP requests in chunks. It takes care of some application-common headers that I need to attach and updating all the necessary places in the GUI.
This component is shared between couple other components for various use-cases. I'm trying to delegate the task of creating HTTP request from a given input to the callers but found out that when the caller does:
var req = $http.get("url", {})
It's already submitting the request.
I'd like the callers to provide a method to generate a list of request objects from the input, and my component will deal with that later (add some headers for example, add success() and error() methods, or submit the requests in batches).
How can I only create the HTTP Request object, without sending it?
You can create wrapper function for "delayed" http request, that would return you preconfigured ready to call function, and use it instead of $http.
Maybe like this:
function dHttp(config) {
return function(options) {
angular.merge(config, options);
return $http(config);
}
}
var req = dHttp({
url: '/some',
data: {test: 21}
});
// later send it
req().then(function(data) {
console.log(data);
});
A plain AJAX can be useful here
xmlhttp.open("GET","a-url",true);
xmlhttp.send();
$http.get() is a declarative form of an ajax open and send.
var reqArr = [];
reqArr.push(xmlhttp.open("GET","a-url",true));
reqArr.push(xmlhttp.open("GET","b-url",true));
reqArr.push(xmlhttp.open("GET","c-url",true));
so you can change the objects as needed and send the ajax later on.

Resources