Bre*_*eli 2 javascript angularjs
我有以下控制器使用服务客户返回客户.问题是它只在第一次运行控制器时执行服务.查看我的服务器,我看到它只执行get请求第一次控制器使用(加载该视图)如果我更改视图并说添加客户并返回到列出客户未更新的视图,因为没有其他获取服务请求.
.controller('searchCTRL', ['$scope', '$http', 'Customers', function($scope, $http, Customers) {
$scope.customers = Customers;
$scope.deleteCustomer = function(id) {
$http.delete('/api/customer/' + id)
.success(function(data) {
$scope.customers.data = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}])
Run Code Online (Sandbox Code Playgroud)
和
.factory('Customers', function($http){
var Customers = {};
$http.get('/api/customer')
.success(function(data) {
Customers.data = data;
})
.error(function(data){
console.log('error: ' + data);
});
return Customers;
});
Run Code Online (Sandbox Code Playgroud)
如果我留在视图上并重新加载页面,它会获得类似的数据,但是对页面的任何后续访问都不再执行获取.任何帮助,将不胜感激.
Angular .factory是一个单身人士,所以它总是只运行一次.此外,该$http
调用是异步的,因此您应该使用promise
以便将数据传输到控制器.请尝试以下方法:
.factory('Customers', function($http, $q){
return function () {
var d = $q.defer();
$http.get('/api/customer')
.success(function(data) {
d.resolve(data);
})
.error(function(data){
console.log('error: ' + data);
d.reject(data);
});
return d.promise;
};
});
Run Code Online (Sandbox Code Playgroud)
并在您的控制器中:
.controller('searchCTRL', ['$scope', '$http', 'Customers', function($scope, $http, Customers) {
Customers().then(function (data) {
$scope.customers = data;
});
...
Run Code Online (Sandbox Code Playgroud)
作为$http
回报承诺,您可以通过以下方式进一步简化.factory
:
.factory('Customers', function($http){
return function () {
return $http.get('/api/customer');
};
})
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅$ http的文档.
归档时间: |
|
查看次数: |
3448 次 |
最近记录: |