当我在服务中执行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 :(得分: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')
}
}
});
答案 1 :(得分: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;
});
}]);