我正在構建一個表單,可以使用AngularJS發送和清除緩存的JSON數據到RESTful Web服務。當我點擊提交時,當前表單數據被緩存在一個JSON對象中,然後通過Web服務發送這些數據。一旦發送,我清除緩存。AngularJS無法在服務內部重複異步功能
我有一個功能,我希望在多個控制器(發送緩存數據)中使用。它循環遍歷緩存,每次發送一個JSON對象。當我在單個控制器中具有該功能時,代碼工作正常。但是,一旦我將它包裝在服務中並通過控制器調用它,我的循環就不再起作用。如果只有一個緩存對象,它運行良好。但是如果超過1,「this.sendCache()」將不會觸發。我相信這與異步函數有關,我不知道該怎麼做。非常感謝幫助!
控制器
app.controller('FormCtrl', function($scope, $filter, $window, getData, Post, randomString, $cordovaProgress, $cordovaDialogs, scService) {
$scope.submitEntry = function() {
var frmData = new Post($scope.postData);
var postCount = window.localStorage.getItem("localPostCount");
postCount ++;
window.localStorage.setItem("localPostCount", postCount);
window.localStorage.setItem("post" + postCount, JSON.stringify(frmData));
scService.sendCache();
};
});
服務
app.service('scService', function ($window, Post, $cordovaProgress, $cordovaDialogs, $timeout) {
this.sendCache = function() {
if(window.Connection){
if(navigator.connection.type != Connection.NONE) {
var postCount = window.localStorage.getItem("localPostCount");
var curCacheObj = new Post(JSON.parse(window.localStorage.getItem("post" + postCount) || '{}'));
if (postCount > 0) {
curCacheObj.$save().then(function(response) {
var servResponse = JSON.stringify(response);
if (servResponse.indexOf("@xmlns:ns3") > -1) {
console.log("Post " + postCount + " sent!");
}
else {
console.log("Unable to post at this time!");
}
}).then(function() {
window.localStorage.removeItem("post" + postCount);
postCount --;
window.localStorage.setItem("localPostCount", postCount);
}).then(function() {
console.log(postCount); //log shows 1
if (postCount > 0) {
this.sendCache(); //yet this won't fire again!
}
else {
$cordovaDialogs.alert('Submission recorded successfully', 'Success', 'OK').then(function() {
console.log('Submission Success');
$window.location.href= 'index.html';
});
}
});
}
else {
$cordovaDialogs.alert('Submission recorded successfully', 'Success', 'OK').then(function() {
console.log('Submission Success');
$window.location.href= 'index.html';
});
}
}
else {
$cordovaDialogs.alert('Your current connection is too slow. Sync at a later time by returning to the app with a better connection.', 'Submission Stored', 'OK').then(function() {
console.log('Submission Cached');
$window.location.href= 'index.html';
});
}
}
};
});
OMG IT WORKS I LOVE YOU!說真的,我永遠不會想到我自己 – shredMER
不要感覺不好。我知道答案,因爲我完成了同樣的事情,哈哈。 –