与promises angularjs有关的麻烦...控制台日志无法使用http请求

时间:2013-11-11 18:22:54

标签: javascript angularjs

我在角度js中发出http请求时遇到了麻烦。我知道正在进行通话,因为我可以在firebug中看到响应,即

 [{"cube":"1" ,"points":"160"},{"cube":"2","points":"690"},{"cube":"3","points":"331"}] 

我将继续本教程link

因此我的代码看起来像这样 注意我把评论放在我遇到麻烦的地方。我的主要问题是为什么console.log没有工作?我怎样才能让它发挥作用?如何将$ scope.usersPerCube分配给网络请求返回的json?

var myApp = angular.module('test', []);

myApp.controller('UserCtrl', function($scope, users) {
   users.getUsers().then(function(data) {
       //not working
       $scope.usersPerCube = data;
       //this isn't getting logged
       console.log(data);
   });
   //this is getting logged and returning [object Object] which is the promise
   console.log(users.getUsers());
})

myApp.factory('users', function($http) {
   return {
     getUsers: function() {
       var url = "http://localhost/index.php/analytics/UsersPerCube"
       return $http.jsonp(url).then(function(result) {
           //this is not getting logged as well...
           console.log(result+ "logging from http");
           return result.data;
       });
     }
   }
});

1 个答案:

答案 0 :(得分:0)

您需要使用JSONP方法吗?有关$http.jsonp parsing JSONP $http.jsonp() response in angular.js的使用情况,请参阅以下问题。

如果您将$ http方法更改为get,它会记录数据并成功设置为范围变量。

Plunker

var myApp = angular.module('test', []);
myApp.controller('UserCtrl', function($scope, users) {
   users.getUsers().then(function(data) {
       //not working
       $scope.usersPerCube = data;
       //this isn't getting logged
       console.log($scope.usersPerCube);
   });
   //this is getting logged and returning [object Object] which is the promise

});

 myApp.factory('users', function($http) {
    return {
      getUsers: function() {
        var url = "data.json?callback=jsonp_callback"
          return $http.get(url).then(function(result) {
          //this is not getting logged as well...
          console.log(result);
          return result.data;
        }, function(result){
          console.log("failed");
        });
     }
   }
 });