Angularjs 服务中的$http返回$$state对象
我正在使用以下代码。我正在读一个json文件名为“hassan.json”。如果我通过$http在controller中读取此文件,则一切正常。但我想使用我从文件中读取的数据,一次又一次地在不同的控制器中使用,所以我为此做了一个服务。但是在服务中,当我通过$http.get()从该json文件读取数据时,作为回报,当我在我的控制器和控制台中调用该服务方法时。log(data)它在控制台“e{$$state:object}”中返回我这个值。 这是控制器: 这是服务我正在使用:Angularjs 服务中的$http返回$$state对象,angularjs,Angularjs,我正在使用以下代码。我正在读一个json文件名为“hassan.json”。如果我通过$http在controller中读取此文件,则一切正常。但我想使用我从文件中读取的数据,一次又一次地在不同的控制器中使用,所以我为此做了一个服务。但是在服务中,当我通过$http.get()从该json文件读取数据时,作为回报,当我在我的控制器和控制台中调用该服务方法时。log(data)它在控制台“e{$$state:object}”中返回我这个值。 这是控制器: 这是服务我正在使用: $http.get(
$http.get().then()
和$http.get().success()
将代码更改为:
var deferred = $q.defer();
$http.get('jsons/hassan.json')
.success(function(data){
this.outData = data;
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
$http.get().then()
和$http.get().success()
将代码更改为:
var deferred = $q.defer();
$http.get('jsons/hassan.json')
.success(function(data){
this.outData = data;
deferred.resolve(data);
})
.error(function(err) {
deferred.reject(err);
});
return deferred.promise;
按如下方式更改控制器:
app.controller('showdata', function($scope, service){
service.getData().then(function(user){
$scope.mydata = (user.data);
console.log(($scope.mydata));
});
});
按如下方式更改控制器:
app.controller('showdata', function($scope, service){
service.getData().then(function(user){
$scope.mydata = (user.data);
console.log(($scope.mydata));
});
});
$http
本身就是一种承诺,因此在$q
中没有必要使用$http
的缓存来重写代码:
app.controller('showdata', function($scope, service){
service.getData().then(function(user) {
// no need to call user.data, service handles this
$scope.mydata = user;
console.log($scope.mydata);
}).catch(function (err) {
// handle errors here if needed
});
});
及
$http
本身就是一种承诺,因此在$q
中没有必要使用$http
的缓存来重写代码:
app.controller('showdata', function($scope, service){
service.getData().then(function(user) {
// no need to call user.data, service handles this
$scope.mydata = user;
console.log($scope.mydata);
}).catch(function (err) {
// handle errors here if needed
});
});
及
由于您的调用是异步的,所以解析后应该有console.log,即$scope.mydata=service.getData()。然后(函数(user){$scope.mydata=(user.data);console.log($scope.mydata));})代码>你能修改我的代码,然后评论它修改了你的原始源代码吗。请在您的控制器中使用修改过的源代码进行测试。如果您的调用是异步的,您应该在解析后使用console.log,即$scope.mydata=service.getData()。然后(函数(用户){$scope.mydata=(user.data);console.log($scope.mydata));})代码>你能修改我的代码,然后评论它修改了你的原始源代码吗。请在您的控制器中使用修改过的源代码测试$http.get()。success()
和error()
不推荐使用(),您应该使用then()
instead@Andriy在v1.6.0中!!我肯定他没有使用v1.6.0@MeTe-30,很抱歉投了反对票,1)没有提到Angular js版本,2)绝对重复使用$q
服务$http.get().success()
和error()
不推荐使用(),您应该使用then()
instead@Andriy在v1.6.0中!!我肯定他没有使用v1.6.0@MeTe-30,抱歉投了反对票,1)没有提到Angular js版本,2)绝对冗余使用$q
服务Brother u在Controller中调用未在服务中任何位置声明的getData方法--->服务。getData不是函数Brother u在Controller中调用未在服务中任何位置声明的getData方法--->服务。getData不是函数