使用缓存数据设置angularjs工厂的正确方法
我刚开始使用Angular.js,我正在尝试建立一个工厂,它将显示缓存的数据,并在接收到数据后用从REST服务检索的数据替换它 为了验证这一点,我只是对“缓存”数据进行硬编码。收到数据后,我希望使用从服务器接收的最新数据更新$scope.directory变量。我要么得到它 这是我的工厂代码:使用缓存数据设置angularjs工厂的正确方法,angularjs,angularjs-service,angularjs-factory,Angularjs,Angularjs Service,Angularjs Factory,我刚开始使用Angular.js,我正在尝试建立一个工厂,它将显示缓存的数据,并在接收到数据后用从REST服务检索的数据替换它 为了验证这一点,我只是对“缓存”数据进行硬编码。收到数据后,我希望使用从服务器接收的最新数据更新$scope.directory变量。我要么得到它 这是我的工厂代码: app.factory('directoryFactory', function ($http) { var factory = {}; factory.directory = [{name: "Test
app.factory('directoryFactory', function ($http) {
var factory = {};
factory.directory = [{name: "Test", ext: "123"},{name: 'Bob', ext: "234"}];
init();
function init() {
$http({
method: 'GET',
url: '{restapiURL}'
})
.success(function (data, status, headers, config) {
factory.directory=data;
})
.error(function (data, status, headers, config) {
console.log('directory fail');
});
}
}
我的控制器具有以下代码:
$scope.directory = directoryFactory.directory;
在我看来,我使用ng repeat列出所有人及其扩展名
我希望在收到数据后立即更新视图。监视factory数据更改的正确方法是什么?您的
$scope.directory
包含两个成功和失败处理程序。由于$http
是异步的,所以您不知道响应应该在什么时候出现,但是如果您使用then(),“promise”会通知您
以下是POST
的示例,但其流程相同:
工厂:
myModule.factory('ajax_post', ['$http', function(_http) {
var path = 'src/php/data.ajax.php';
return{
init: function(jsonData){
var _promise= _http.post(path,
jsonData
,{
headers: {
'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'
}
}
);
return _promise;
}
}
}]);
var _promise= ajax_post.init(jsonData);
_promise.then(function (result) {
//do something with your result
},
function (error) {
alert(error.message);
}
);
在控制器中:
myModule.factory('ajax_post', ['$http', function(_http) {
var path = 'src/php/data.ajax.php';
return{
init: function(jsonData){
var _promise= _http.post(path,
jsonData
,{
headers: {
'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'
}
}
);
return _promise;
}
}
}]);
var _promise= ajax_post.init(jsonData);
_promise.then(function (result) {
//do something with your result
},
function (error) {
alert(error.message);
}
);
使用。然后
帮助返回http响应。显示了一个非常好的教程,包括$q
方法。如果我有时间,我可以发布一个plunk,但这些都是很好的开始。我可以从$http调用中很好地获得目录响应,但为了显示新数据,我必须在控制器中包含以下内容:$scope.directory=directoryFactory.directory()$超时(函数(){$scope.directory=directoryFactory.directory();},2000);我想这可以归结为:当directoryFactory.directory更新时,如何触发$scope.directory查找最新值。最后,我使用$broadcast让控制器知道第二组数据已加载。