Zach Moshe
Zach Moshe

Reputation: 2980

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?

Upvotes: 2

Views: 53

Answers (2)

devbd
devbd

Reputation: 431

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.

Upvotes: 0

dfsq
dfsq

Reputation: 193281

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);
});

Upvotes: 2

Related Questions