2016-11-26 53 views
2
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); 
    }); 
}; 

的数据被存储到变量但最终不传送到控制器的服务。 有什么指导?你的服务

回答

0

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

+0

$ HTTP默认返回一个承诺......检查angularjs文档... 尝试,但我得到的错误.....然后()不能设置为未定义。 你可以用工作代码显示一个jsfiddle吗?因为我的工作不在工作 –

+0

@ScienCeSubject检查出更新的答案&plunkr :) –

+0

它有点帮助...改变了我的逻辑,以实现我想要的...但仍然thnx帮助我 –

相关问题