Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS http return value

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.

My first attempt was:

this.readParameter = function(key) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
    return response.data;
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};

But of course it does not work because of Angular async features (response.data is undefined)

What is the way to do it? I just want to return the value (string), so I can use this function like

var a = readParameter("key1")
like image 308
Carlos Avatar asked Oct 12 '15 12:10

Carlos


People also ask

Which object does the http GET () function return?

HttpClient.get() returns response datalink HttpClient.get() returns the body of the response as an untyped JSON object by default.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

What is HTTP request in angular?

HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.


2 Answers

What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.

Delegator pattern works great here to assign $http task to some service and use callback method for response.

Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)

Basic example of Callback

var myVariable = '';
function myFunction (key, callback) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
      callback(response);
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};

function myCallbackFunction(response) {
   myVariable = response.data; // assign value to variable
   // Do some work after getting response
}

myFunction('MY_KEY', myCallbackFunction);

This is basic example to set value but instead use callback pattern from above example.

var myvariable = '';
function myFunction (key) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
      myvariable = response.data; // set data to myvariable
      // Do something else on success response
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};
myFunction('MY_KEY');
like image 150
Sarjan Desai Avatar answered Oct 02 '22 16:10

Sarjan Desai


Don't try to mix async and sync programming. Instead use a callback to use like

readParameter("key1", callback)

for example:

    this.readParameter = function(key, callback) {
  $http({
    method: "GET",
    url: "XXXXXXX",
    headers: { 'Content-Type': 'application/json' }
  }).then(function successCallback(response) {
    callback(response)
  }, function errorCallback(response) {
    throw new Error("Error");
  })
};
like image 28
Hüseyin Zengin Avatar answered Oct 02 '22 17:10

Hüseyin Zengin