【问题标题】:working with services for data manipulation angular使用服务进行数据操作
【发布时间】:2017-04-10 19:34:35
【问题描述】:
app.service('cityService',['$http',function($http){
this.get = function(){
        $http({
            method : 'get',
            url : API_SERVER+'city/'
        }).success(function(response){
            console.log(response);
            return response;
        }).error(function(response){
            console.log(response);
        });
    };
 }

我正在尝试使用该服务从服务器获取数据,但问题是当我使用该服务将数据存储在范围变量中时。我得到undefined。我正在接收数据,因为数据显示在控制台中+当我添加控制器时服务也在工作,但数据没有保存在任何变量中。我使用$timeout 来延迟检查变量,但仍然没有运气。我也使用了.then(),但是当我添加服务时它显示undefined 服务......

app.controller('Controller',['cityService',function(cityService){
$scope.temp = {};
$scope.temp = cityService.get();
}]);

无论如何要将数据从服务传递到控制器? 笔记: 还尝试将数据存储到服务变量中并返回服务变量

this.var = ''
this.get = function(){
    $http({
        method : 'get',
        url : API_SERVER+'city/'
    }).success(function(response){
        this.var = response
        console.log(this.var);
        return this.var;
    }).error(function(response){
        console.log(response);
    });
};

数据存储到变量中,但最终没有传递给控制器​​。 有什么指导吗?

【问题讨论】:

    标签: javascript angularjs asynchronous angularjs-service


    【解决方案1】:

    您的服务的this.get 方法应该返回一个promise 对象,以便调用者可以调用.then 方法获取response链接承诺时间>。

    服务

    app.service('cityService', ['$http', function($http) {
        this.get = function() {
            return $http.get(API_SERVER + 'city/');
            //below would work but use upper one smaller version
            //return $http({
            //    method : 'get',
            //   url : API_SERVER+'city/'
            //});
        };
    }]);
    

    然后在访问控制器内部的数据时,您可以将 .then 函数放在它上面以获取它的响应。

    此外,您还没有在控制器 DI 数组中添加 $scope 依赖项。

    app.controller('Controller', ['cityService', '$scope',
      function(cityService, $scope) {
        $scope.temp = {};
        cityService.get().then(function(response) {
          console.log(response)
          $scope.temp = response.data;
        });
      }
    ]);
    

    Demo Here

    【讨论】:

    • $http 默认返回一个承诺...检查 angularjs 文档...尝试但我得到错误.....then() 无法设置为未定义。你能用工作代码展示一个jsfiddle吗?因为我的不工作
    • @ScienCeSubject 查看更新的答案和 plunkr :)
    • 它有点帮助...改变了我的逻辑以实现我想要的...但仍然感谢帮助我
    猜你喜欢
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多