Explain Codes LogoExplain Codes Logo

Angularjs passing data to $http.get request

javascript
promises
callbacks
async-programming
Nikita BarsukovbyNikita Barsukov·Jan 7, 2025
TLDR

In AngularJS, send data with $http.get via the params object as URL query strings, like this:

$http.get('/api/data', { params: { key: 'value' } }) .then(response => console.log(response.data));

This lets AngularJS neatly append ?key=value to your URL, ferrying your data to the server like a well-trained data-pigeon.

Creating, sending and plucking the data-pigeon

When sending a GET request using $http, we use the params object to encode our data, just like attaching a message to a homing pigeon's leg. Keep your messages brief and succinct to ensure delivery.

Decking out your pigeons with cool hats

We can also attach headers to provide more information about the request:

$http.get('/api/data', { params: { key: 'value' }, headers: {'Accept': 'application/json'} }).then(response => /* Pretend this is a pigeon food factory */);

(Our pigeon now wears a swanky hat labeled 'Accept: application/json'.)

Async pigeon flight

In the asynchronous world, we use Promises with $q to ensure successful data delivery:

function getDataPigeon(params) { var pigeon = $q.defer(); $http.get('/api/data', {params: params}).then( function successfulPigeonArrival(response) { pigeon.resolve(response.data); // Pigeon relays its secret message }, function failedPigeonDelivery(response) { pigeon.reject('Pigeon ran into a window: ' + response.status); // Sad pigeon noise 🐦💥🪟 } ); return pigeon.promise; }

An aviary full of data-pigeons

Creating an AngularJS service encapsulates $http functionality for reuse, leading to cleaner, modular code:

app.service('PigeonPost', function($http) { this.consultThePigeons = function(params) { return $http.get('/api/data', {params: params}).then(response => response.data); }; });

Looking after your pigeon flock

Server-side pigeon landing pads

Server-side, you need a landing pad for the arriving pigeons. In PHP, this is done using $_GET.

// PHP landing pad for our datapigeon $pigeonMessage = $_GET['playerId'];

URL pigeon paths and server compatibility

Ensure URLs are encoded correctly and are compatible with the server's query string expectations.

$http.get('/api/pigeonpost/' + encodeURIComponent(pigeonId));

Taking care of your data-pigeons

Pigeon radio preferences

Data-pigeons can carry additional data, like radio frequency preferences, in their params:

$http.get('/api/data', { params: { RadioChannel: 'SmoothJazz', volume: '11' } }) .then(response => /* All pigeons appreciate smooth jazz */);

Pigeon Care Hotline

Ensure to call the pigeon care hotline if things go amiss with .catch() or the error management function of .then().

$http.get('/api/data', { params: { key: 'value' } }) .then(response => /* Good pigeon */, error => /* Naughty pigeon */);