te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - AngularJS http return value - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS http return value - Stack Overflow

programmeradmin4浏览0评论

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")

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")
Share Improve this question edited Oct 12, 2015 at 12:23 Muhammad Usman 1,3625 gold badges19 silver badges35 bronze badges asked Oct 12, 2015 at 12:06 CarlosCarlos 1,8225 gold badges24 silver badges42 bronze badges 3
  • There is no other way than to return the $http promise and use then() with readParameter() to get the data you received asynchronously. – ryeballar Commented Oct 12, 2015 at 12:10
  • But is it possible to wrap it into a function so I can use it directly like var a = readParameter("myKey")? Or must I forget it? Thank you – Carlos Commented Oct 12, 2015 at 12:26
  • 1 No. Don't treat asnychronous as if it is synchronous, you might need some refresher on what asynchronous and synchronous is. – ryeballar Commented Oct 12, 2015 at 12:31
Add a ment  | 

3 Answers 3

Reset to default 8

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

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

I resolve this by using promise:

Example :

in Service (invoicesAPIservice => invoicesapiservice.js) you use:

angular.module('app')
.service('invoicesAPIservice', function ($http) {
     this.connectToAPI= function () {

     return new Promise(function(resolve,reject){
            var options = {
                method:'GET',
                url :'',
                headers:{
                    'X-User-Agent': '....',
                    'Authorization': '....',
                }
            };

           $http(options).then(function successCallback(response) {
                    resolve(response);
                //console.log(response);
            },function errorCallback(response) {
                reject(response);
            })
     });
});

});

and in your Controller (mainCtrl=> mainCtrl.js):

angular.module('app').controller('mainCtrl', function($scope,invoicesAPIservice) {
  $scope.connectToAPI=function () {           
      invoicesAPIservice.connectToAPI().then(function (content) {
           console.log(content.statusText);
      }.catch(function (err) {
        //console.log(err);
        alert("Server is Out");
    });
 }

});

And in your page : index.html:

<button ng-click="connectToAPI()"></button>

:)

发布评论

评论列表(0)

  1. 暂无评论