我在使用本地存储和Ionic应用程序时遇到了一些麻烦。事情很简单 - 我想将来自sql数据库的所有数据存储到设备中,然后在设备没有网络时显示它。
所以我从中获取数据的代码如下所示:
controllers.js:
$http.get('http://someurl.php?type=json')
.success(function(data) {
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
那么有人可以帮我解决这个问题吗?
谢谢!
答案 0 :(得分:1)
我可以建议您使用一些插件用于DB但是使用localstorage你必须传递(并安装)这个:
angular-local-storage
然后在你的JS中使用它:
$http.get('http://someurl.php?type=json')
.success(function(data) {
//test if is online or offline and the do something
if($rootScope.isOnLine)
localStorageService.set("nameofkey", { data:data }); //here you store in your localstorage ... remeber to inject it as dependency
$scope.info = data;
})
.error(function(response) {
$scope.info = "Error";
});
然后,如果您想知道您的离子应用程序是在线还是离线,您可以使用此插件:http://ngcordova.com/docs/plugins/network/
"use strict";
// Ionic Starter App
angular.module("myapp", ["ionic",
"ionic.service.core",
"ngCordova",
"ionic.service.push",
"ngResource",
"LocalStorageModule",
"ionic-native-transitions",
"angularMoment"])
.run(["$ionicPlatform", "authService", "$rootScope", "$timeout", "$cordovaSpinnerDialog", "$window", "$cordovaNetwork", "$state", "ScanService", "$cordovaToast", "localStorageService", "DB",
function ($ionicPlatform, authService, $rootScope, $timeout, $cordovaSpinnerDialog, $window, $cordovaNetwork, $state, ScanService, $cordovaToast, localStorageService, DB) {
$ionicPlatform.ready(function () {
$rootScope.isOnLine = true;
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (ionic.Platform.isIPad() &&
window.cordova &&
window.cordova.plugins &&
window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
// CONNECTION STATE /////////////////////////////////////////////
if ($cordovaNetwork) {
//listen for OnLine event
$rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
var onlineState = networkState;
$rootScope.isOnLine = true;
});
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
var offlineState = networkState;
$rootScope.isOnLine = false;
});
}
//////////////////////////////////////////////////////////////////
});
}]);
如果没有连接,这是服务使用它进行呼叫http或本地服务的例子:
"use strict";
angular
.module('gestione')
.factory("ScanService", ["$q", "$resource", "enviroment", "$rootScope", "localStorageService", "DB",
function ($q, $resource, enviroment, $rootScope, localStorageService, DB) {
var self = this;
// Private Fileds
var _serviceBase = "api/Scan/";
var _serviceBaseBarScan = "api/BarScan/";
var _serviceBaseCount = "api/Scan/Count";
var _serviceBaseLast = "api/Scan/Last";
var _serviceBaseAll = "api/Scan/All";
// Private Method
var _resource = $resource(enviroment.apiUrl + _serviceBase, { skip: '@skip', take: '@take' }, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
var _resourceLast = $resource(enviroment.apiUrl + _serviceBaseLast, {}, {
query: { method: "GET", isArray: false }
});
var _resourceAll = $resource(enviroment.apiUrl + _serviceBaseAll, {}, {
create: { method: "POST", isArray: true }
});
var _resourceCount = $resource(enviroment.apiUrl + _serviceBaseCount, {}, {
query: { method: "GET", isArray: false }
});
var _resourceBar = $resource(enviroment.apiUrl + _serviceBaseBarScan, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST", isArray: false }
});
return {
Get: function (skip, take) {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resource.query({ skip, take }).$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC ;").then(function (result) {
var scan = DB.fetchAll(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetLast: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceLast.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT * FROM Scan ORDER BY ROWID DESC LIMIT 1 ;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
GetNotSync: function () {
return DB.Query("SELECT * FROM Scan WHERE sync = ? ", ['false']).then(function (result) {
return DB.fetchAll(result);
});
},
CheckInOrOut: function (item) {
return DB.Query("SELECT * FROM Scan WHERE idTicket = ? ORDER BY ROWID DESC LIMIT 1;", [item.IdTicket]).then(function (result) {
return DB.fetch(result);
});
},
Count: function () {
var deferred = $q.defer();
// IS ONLINE
if ($rootScope.isOnLine) {
_resourceCount.query().$promise.then(function (resp) {
deferred.resolve(resp);
}).catch(function (err) {
deferred.reject(err);
});
} else { // OffLine
DB.Query("SELECT COUNT(*) FROM Scan;").then(function (result) {
var scan = DB.fetch(result);
deferred.resolve(scan);
}, function (err) {
deferred.reject(err);
});
}
return deferred.promise;
},
Save: function (scan) {
var deferred = $q.defer();
//We're OnLine
if ($rootScope.isOnLine) {
_resource.create(scan).$promise.then(function () {
scan.sync = true;
}).catch(function () {
scan.sync = false;
}).finally(function () {
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
});
} else { // OffLine
scan.sync = false;
DB.Insert(scan).then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
}
return deferred.promise;
},
Sync: function () {
var self = this;
var deferred = $q.defer();
var allPromise = [];
//get all stored scans
self.GetNotSync().then(function (scanList) {
// send them to the server
if (scanList && scanList.length > 0)
_resourceAll.create(scanList).$promise.then(function (resp) {
//cicle on each record returned from server
resp.forEach(function (item) {
if (item) {
//prepare query
var update_query = "UPDATE Scan SET sync= 'true' WHERE idTicket= " + item.idTicket;
//set sync to true on records
allPromise.push(DB.Update(update_query));
}
});
}).catch(function (err) {
allPromise.push(deferred.reject(err));
});
}).catch(function (error) { allPromise.push(deferred.reject(error)); });
return $q.all(allPromise);
},
GetBarScan: function () {
return _resourceBar.query();
},
SaveBarScan: function (barscan) {
var deferred = $q.defer();
_resourceBar.create(barscan).$promise.then(function (record) {
deferred.resolve(record);
}).catch(function () {
deferred.reject();
});
return deferred.promise;
}
};
}
]);