AJAX in Angular

Posted by Joe Enos on June 23, 2021 · 3 mins read

Regular GET/POST

$http({
method: "POST",
url: "someUrl",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
data: JSON.stringify({ name: "John Doe" })
}).then(function(response) {
console.log("Successful response: " + response);
}, function(response) {
console.log("Error response: " + response);
});

JSONP (in a factory)

// Make sure you include it in DI:  app.factory("myFactory", function ($http, $sce) {
factory.getSomething = function (callback) {

const URL = "http://something.../?param=someval&param2=otherval";

var url = $sce.trustAsResourceUrl(URL);

$http.jsonp(url, {
jsonpCallbackParam: "callback"
}).then(function (response) {
console.log("Successful response: " + response);
}, function (response) {
console.log("Error response: " + response);
});
};
/*
response:
    data -" {string|Object} -" The response body transformed with the transform functions.
    status -" {number} -" HTTP status code of the response.
    headers -" {function([headerName])} -" Header getter function.
    config -" {Object} -" The configuration object that was used to generate the request.
    statusText -" {string} -" HTTP status text of the response.
*/