简体   繁体   中英

How to return value from inner $http-function in outer function in angular?

I am using an Angular service as an interface for API calls. In this case JavaScript's asynchronous nature makes this difficult. Do you have any suggestions to how I should do it?

function getOrder(orderId) {
    $http({
        method: 'GET',
        url: '<api-url> + orderId'
    }).success(function (result) {
        /* --- getOrder should return parameter 'result' --- */
    });
}

Better return the promise:

function getOrder(orderId) {
  return $http({
    method: 'GET',
    url: '<api-url>' + orderId
  });
}

Then, when calling:

getOrder("1").then(function(response) {
  // response.data contains the returned data
});

See https://docs.angularjs.org/api/ng/service/$http#general-usage


Please note the deprecation notice about success and error .

Are you familiar with callback functions and promises? I think you should have an additional parameter in you getOrder function, the callback function, which you should call with the results or the error message with.

Here is an introduction for this: http://recurial.com/programming/understanding-callback-functions-in-javascript/

or just return the promise itself, as mentioned above!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM