I'm working in a team that is building an Android application using web technologies (angular.js, etc.) and Phonegap to turn the project into an Android application. We're fairly new to AngularJS and have run into a problem integrating services into our code. We are trying to do some basic server calls, which are working as regular code, but we are trying to make them a service so we don't duplicate this all over the place. We're using a Phonegap localStorage plugin to store the ID of a database object on the phone's HTML5 local storage.
Here is our code:
.service("contactServer", function($resource, $http, baseUrl) {
// Initialize resource and modify methods s.t. create POSTS and save PUTS.
this.post = function() {
alert("Starting post");
var item = {"name": model.userName, "position": model.position};
alert("Creating resource");
var serverResource = $resource(baseUrl,
{create: {method: "POST"}, save: {method: "PUT"}});
alert("Created resource");
new serverResource.create(item).then(function(data, status, headers, config) {
alert("id: " + data._id);
window.localStorage.setItem("DBid", data._id);
}, function(data, status, headers, config) {
alert(JSON.stringify(['Error', data, status, headers, config]))
})
}
this.put = function() {
alert("Starting put");
var item = {"name": model.userName, "position": model.position, "id": window.localStorage.getItem("DBid")};
alert("Creating resource");
var serverResource = $resource(baseUrl + "/:id", {id: "@id"},
{create: {method: "POST"}, save: {method: "PUT"}});
alert("Created resource");
new serverResource(item).save().then(function(data, status, headers, config) {
alert(JSON.stringify(['Success', data, status, headers, config]));
}, function(data, status, headers, config) {
alert(JSON.stringify(['Error', data, status, headers, config]));
})
}
})
baseUrl is a URL link to our database. We call the services here:
.run(function(contactServer) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if (window.localStorage.getItem("DBid") == null) {
alert("no DBid");
contactServer.post();
}
else {
alert("Retrieved stored DBid: " + window.localStorage.getItem("DBid"));
contactServer.put();
}
}
})
deviceready is a Phonegap event that fires when the application has loaded on the user's phone. We want to call these services in several of our controllers, but also initially during this run function.
The code fires up to the "starting post" alert after being called in the run function, but then breaks. Are we using $resource wrong? (It is correctly listed as a dependency). Are we implementing the service wrong?