2016-04-15 84 views
1

当我在服务中执行http.get时,我无法使用{{gs}}更新视图中的$ scope.gs变量。我尝试阅读一些答案,但他们似乎暗示了这种方法。请帮助...

我的服务方法如下:

app.service('myService', function($http, $rootScope) { 
this.getData = function(key){ 
    return $http.get('/myapp/stocklist/AMZN'). 
    then(function(data) {  
    return data; 
    }); 
    } 
    //return this; 
}); 

我的控制器:

app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){ 
myService.getData($scope.mySelected).then(function(codes){ 
$scope.gs= codes; 
}); 
}]); 

我不知道我是否应该使用工厂,而不是服务于这一点。你能咨询一下吗?

+0

控制台错误??? – TKHN

回答

0

可以使用$q

app.service('myService', function($http, $rootScope, $q) { 
    return { 
     getData: function (key) { 
      var deffered = $q.defer(); 

      $http.get('/myapp/stocklist/AMZN') 
       .then(function (result) { 
        deffered.resolve(result.data); 
       }, function (error) { 
        deffered.reject(error); 
       }); 

      return deferred.promise 
     } 
    } 
}); 

或调整服务

app.service('myService', function($http, $rootScope, $q) { 
    return { 
     getData: function (key) { 
      $http.get('/myapp/stocklist/AMZN') 
     } 
    } 
}); 
0

然后使用两次。尝试

服务

app.service('myService', function($http, $rootScope) { 
    this.getData = function(key){ 
     return $http.get('/myapp/stocklist/AMZN');  
    }); 
}); 

控制器

app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){ 
    myService.getData($scope.mySelected).then(function(response){ 
      $scope.gs= response.data; 
    }); 
}]); 
+0

嗨Lukszaq,谢谢你的回答。这是行得通的,但我也想对服务中的数据做一些处理,以便我可以在两个不同的控制器中使用它。再次感谢你。 – sachin

+0

@sachin U可以在你想要的尽可能多的控制器中使用服务。不需要改变它。 – Lukaszaq