Javascript 使用服务进行数据操作

Javascript 使用服务进行数据操作,javascript,angularjs,asynchronous,angularjs-service,Javascript,Angularjs,Asynchronous,Angularjs Service,我试图使用该服务从服务器获取数据,但问题是当我使用该服务将数据存储在scope变量中时。我得到未定义的。我正在接收数据,因为当我添加控制器时,数据显示在控制台+服务也在工作,但数据没有保存在任何变量中。我使用了$timeout来延迟变量的检查,但仍然没有成功。我还使用了.then(),但当我添加服务时,它会显示服务的未定义 app.service('cityService',['$http',function($http){ this.get = function(){ $htt

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

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);
        });
    };
 }
是否仍要将数据从服务传递到控制器? 注: 还尝试将数据存储到服务变量中并返回服务变量

app.controller('Controller',['cityService',function(cityService){
$scope.temp = {};
$scope.temp = cityService.get();
}]);
数据存储在变量中,但最终不会传递给控制器。
有什么指导吗?

这个。你的服务的get
方法应该返回一个
promise
对象,以便调用者可以调用
。然后
方法获取
响应
或链接承诺

服务

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);
    });
};
然后,在访问控制器内的数据时,您可以将
。然后
函数放置在控制器上,以获得控制器的响应

此外,您没有在控制器DI阵列中添加
$scope
依赖项

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/'
        //});
    };
}]);

$http默认返回承诺…检查angularjs文档。。。已尝试,但出现错误…..然后()无法设置为未定义。你能用工作代码展示一个JSFIDLE吗?因为我的不是working@ScienCeSubject查看更新的答案&plunkr:)这有点帮助。。。改变了我的逻辑来实现我想要的。。。但还是感谢你帮了我
app.controller('Controller', ['cityService', '$scope',
  function(cityService, $scope) {
    $scope.temp = {};
    cityService.get().then(function(response) {
      console.log(response)
      $scope.temp = response.data;
    });
  }
]);