【问题标题】:Angularjs Ionic JSON object not returning dataAngularjs Ionic JSON对象不返回数据
【发布时间】:2016-02-05 18:48:21
【问题描述】:

我正在尝试从 Web 服务取回数据,我必须首先从控制器调用数据,这里是代码

$http({
method: 'POST',
url: 'https://url_json.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset-UTF-8'},
transformRequest: function(obj) {
    var str = [];
    for(var p in obj)
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
},
  data: paramsVal
}).then(function(response){

$scope.myData = response.data.PlaceDetailsResponse.results[0].first_name;

console.log('my data',$scope.myData);
});

}

但我想在控制器之间共享数据,所以我认为 service 是最好的选择,所以在我的 services.js 中我有:

.factory('userService', function($http){
return {
    getUsers: function(){
        return $http.post("https://url_json.php",
            {entry : 'carlo' ,
            type:'first_name',
            mySecretCode : 'e8a53543fab6f00ebec85c535e' 
        }).then(function(response){

            users = response;
            return users;
        });
    }
}

})

但是当我使用var user = userService.getUsers(); 从控制器调用它时,在控制台中返回以下内容:

user is [object Object]

我只看到了 chrome 中的检查元素:

user is Promise {$$state: Object}

当我深入了解 Promise 数据值 = "" 时,也在 chrome 中。

谁能看看我的服务,看看我做错了什么。

谢谢

【问题讨论】:

    标签: javascript angularjs json ionic-framework


    【解决方案1】:

    .then 返回一个承诺。你爱上了explicit promise construction antipattern

    getUsers: function(){
        return $http.post("https://url_json.php",
            {entry : 'carlo' ,
            type:'first_name',
            mySecretCode : 'e8a53543fab6f00ebec85c535e' 
        })
    }
    

    以上就是你所需要的。然后,在您的控制器中:

    userService.getUsers()
    .then(function(response) {
      $scope.data = response.data; // or whatever
    });
    

    我建议查看John Papa AngularJS style guide。他有很多关于获取服务数据、在控制器中使用它等的信息。

    【讨论】:

      【解决方案2】:

      在您的控制器中,您必须通过解析 getUsers 的承诺返回来分配用户变量,如下所示:

      $scope.user = [];
      $scope.error ="";
      
      userService.getUsers().then(function(data){
        $scope.user = data
      },function(err){
         $scope.error = err; 
      });
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-14
        相关资源
        最近更新 更多