在AngularJS中从$ http服务设置$ scope值的最佳方法

时间:2015-12-29 16:08:10

标签: javascript angularjs http asynchronous

我愿意从AngularJS中的$ http服务获取一个值,并将其设置在$ scope.listing中。因为这是异步操作,所以在加载页面时$ scope.listing为空。我看到一些使用promise和factory的实现来解决它,但这对我来说感觉有些过分。有一种优雅的方式吗?

看起来像是:

$http.get('/getlisting/')
.success(function(response) {
            $scope.listing = response;
    })
console.log ($scope.listing) // is empty

3 个答案:

答案 0 :(得分:1)

更改下面的代码

In [2]: class A():
    def a(self, a=0):
        print(a)
   ...:

In [3]: def a():
   ...:     pass
   ...:

In [4]: class B():
   ...:     pass

In [5]: A.a(B())
0

In [6]: A.a
Out[6]: <function __main__.A.a>

您的当前console.log甚至在响应来自服务器之前就已执行,因此它不会打印任何内容...... 如果你在$http.get('/getlisting/') .success(function(response) { $scope.listing = response; console.log ($scope.listing) // is empty }) 内移动它,你会看到打印到控制台的值

答案 1 :(得分:0)

如果您希望在用户到达该特定页面时填充$ scope.listing,您可以利用ui-router的解决方案。您基本上是告诉路由器不允许用户转到该页面,直到从您的$ http呼叫返回所请求的数据(列表)。

请参阅: http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/

答案 2 :(得分:-1)

始终使用服务和原语来处理http调用。

angular.module('App').factory('Request',['$q','$http',function($q,$http){
  return {
    send : function(conf){
      var defer = $q.defer();  
      $http(conf).success(function(response) {
          defer.resolve(response);
      }).error(function(err){
          defer.reject(err);
      });
      return defer.promise;
    }
  };
}])

并在您的控制器中

angular.module('App').controller('MainCtrl',['$scope','Request',function($scope,Request){
 var conf = {
   url : 'some url',
   method : 'GET/POST/PUT/DELETE etc...',
   data : {some : 'data'}
 }; 

 Request.send(conf).then(function(response){
    // todo handle success response here 
 }).catch(function(err){
    // todo handle http error here
 });
}]);
相关问题