1

我在 Angular js 中发出 http 请求时遇到了麻烦。我知道正在拨打电话,因为我可以在萤火虫中看到响应,

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

我要关闭本教程,链接

因此我的代码看起来像这样。
请注意,我在遇到问题的地方发表了评论。我的主要问题是为什么 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;
       });
     }
   }
});
4

1 回答 1

0

是否需要使用 JSONP 方法?请参阅以下有关在 angular.js 中使用$http.jsonp 解析 JSONP $http.jsonp() 响应的问题

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

普朗克

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");
        });
     }
   }
 });
于 2013-11-11T18:52:50.113 回答