我几天来一直在努力解决这个问题,似乎无法找到解决方案。 我在我的视图中有一个简单的列表,从MongoDB获取,我希望每当我调用delete或update函数时它都会刷新。 虽然看起来很简单,我应该能够在同一范围内调用先前声明的函数,但它不起作用。
我尝试在第三个服务上设置getDispositivos,但随后注入全部搞砸了。将函数简单地声明为var function(){...},但它也不起作用。
感谢任何帮助。
这是我的代码:
var myApp = angular.module('appDispositivos', []);
/* My service */
myApp.service('dispositivosService',
['$http',
function($http) {
//...
this.getDispositivos = function(response) {
$http.get('http://localhost:3000/dispositivos').then(response);
}
//...
}
]
);
myApp.controller('dispositivoController',
['$scope', 'dispositivosService',
function($scope, dispositivosService) {
//This fetches data from Mongo...
$scope.getDispositivos = function () {
dispositivosService.getDispositivos(function(response) {
$scope.dispositivos = response.data;
});
};
//... and on page load it fills in the list
$scope.getDispositivos();
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo);
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
};
$scope.removeDispositivo = function (id) {
dispositivosService.removerDispositivo(id);
$scope.getDispositivos(); //... here
};
$scope.editDispositivo = function (id) {
dispositivosService.editDispositivo(id);
$scope.getDispositivos(); //... and here.
};
}
]
);
答案 0 :(得分:0)
在服务上
this.getDispositivos = function(response) {
return $http.get('http://localhost:3000/dispositivos');
}
控制器上的
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo).then(function(){
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
});
};
答案 1 :(得分:0)
没有一种解决方案有效。后来我发现GET请求确实以异步方式执行。这意味着它在POST请求完成之前将数据加载到$ scope中,因此不包括刚刚包含的新数据。
解决方案是使用$ q模块同步任务(有点像多线程编程),并使用延迟对象和承诺。所以,在我的服务上
.factory('dispositivosService',
['$http', '$q',
function($http, $q) {
return {
getDispositivos: function (id) {
getDef = $q.defer();
$http.get('http://myUrlAddress'+id)
.success(function(response){
getDef.resolve(response);
})
.error(function () {
getDef.reject('Failed GET request');
});
return getDef.promise;
}
}
}
}
])
在我的控制器上:
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo)
.then(function(){
dispositivosService.getDispositivos()
.then(function(dispositivos){
$scope.dispositivos = dispositivos;
$scope.dispositivo = '';
})
});
};
做出我的回应'对象一个$ q.defer类型对象,然后我可以告诉Angular响应是异步的,然后是.then(---)。then(---);当异步请求完成时,逻辑完成任务。