What I'm trying to do is create a kind of a storageservice in which I use a SQLite database to store key and value pairs after which I can retrieve them based on the key. To achieve this I set up the following code:
.service('StorageService', function($cordovaSQLite, $q) {
if(window.cordova) {
db = $cordovaSQLite.openDB("vouchers.db");
} else {
db = window.openDatabase("vouchers.db", "1.0", "Vouchers db", -1);
}
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS vouchers (key text, value text)");
return {
getItem: function(item) {
var query = "SELECT key, value FROM vouchers WHERE key = ?";
$cordovaSQLite.execute(db,query,[item]).then(function(result) {
console.log(result.rows[0].value);
return result.rows[0].value;
});
},
setItem: function(item, data) {
var query = "INSERT INTO vouchers (key, value) VALUES (?,?)";
return $cordovaSQLite.execute(db, query, [item, data]);
}
};
})
Now, most of this stuff is working great. I can store items in the db and even retrieve and log them from inside the function as you can see on the following line:
console.log(result.rows[0].value);
When I log this I get the expected value, but when I return it and log it in the controller where I'm using this service it's remaining undefined. The code in my controller looks as follows:
var test = StorageService.getItem("testje");
console.log(test);
Please note that there are NO console errors. Just two logs. One from the controller that is undefined, and one from the service that returns the value as intended:
controllers.js:465 undefined
services.js:122 dit is een testje!
I was hoping anyone can tell what is going wrong here. If there's any info or code that can be helpful and I left out, let me know.
That's because your getItem: function(item) { uses a promise to retrieve the results.
Try to change your code to this instead:
getItem: function(item) {
var query = "SELECT key, value FROM vouchers WHERE key = ?";
return $cordovaSQLite.execute(db,query,[item]);
});
and call your service this way:
StorageService.getItem("testje").then(function(result){
console.log(result);
});
You'll be able to view the results then.
I suggest you to study some basic principles of promises: you'll encounter them very often if you use $http get and post requests and any other async stuff in javascript.
Related
So in my angular JS web app, I have a function that calls on a node in the firebase database called orderedPlayers and returns it as an array as follows:
$firebaseArray(orderedPlayers)
.$loaded(function(loadedPlayers) {
// function in here
});
When attempting to do something similar in the cloud function I am experiencing problems. Is there a way to return the the players node as an array?
I know i can access the database as follows:
admin.database().ref('orderedPlayers');
but the $firebaseArray doesnt work.
These docs can help: https://firebase.google.com/docs/database/admin/retrieve-data
snapshot.val() will return an object that can be referenced as a key-value array. In your case:
admin.database().ref('orderedPlayers').on("value", function(snapshot) {
var loadedPlayers = snapshot.val();
//access your players here
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
To the best of my knowledge cloudfunctions does not include firebaseArray. You can instead just make the players children into an array.
so:
let yourArray = [];
admin.database().ref('orderedPlayers').once('value').then(snap => {
snap.forEach(childSnap => {
yourArray.push(childSnap));
});
});
or you can use the children:
let yourArray = [];
admin.database().ref('orderedPlayers').on('child_added',snap => {
yourArray.push(snap);
});
*on('child_added') will always be called at least once so it removes the need to loop over the children.
If you want to query the database by a specific value you just add something like orderByChild('order') after the ref and before calling once or on
I have this problem with kinvey backend,
I'm trying to fetch data from my collection but it doesn't work for me. here is my code :
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
Can you help me please
If you let run the code you have posted then consider four things:
Make sure you have Kinvey implemented:
<script src="https://da189i1jfloii.cloudfront.net/js/kinvey-html5-sdk-3.10.2.min.js"></script>
Make sure you have initialized the Kinvey service before:
// Values shown in your Kinvey console
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
Make sure you are logged in with a user that has the rights to read your collection (should be fine using the All Users role (default)):
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
})
.catch(function(error) {
console.log (error);
});
Output the return result to see whats coming back. To make sure you do the query AFTER successful login, paste you query inside the .then function of login.
I'm not sure if your query is valid unter 3.x since a lot has changed and I'm not working with older Kinvey versions.
So that all together would look like this:
// Initialize Kinvey
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
// Login with already registered user
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
// Your query
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// Output of returning result
console.log (entity);
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
})
.catch(function(error) {
console.log (error);
});
There are now three return sets possible:
Nothing (as you say) -> Something missing/wrong in the code (compare yours with mine)
Empty array: Your query didn't find anything, adapt the search value(s)
One or more entries in the array -> All fine, what you were looking for!
Hope that helps!
When querying by _id there is a built in method: http://devcenter.kinvey.com/angular/guides/datastore#FetchingbyId
Try switching to var stream = dataStore.findById('entity-id');
Also check to make sure you don't have any preFetch or postFetch BL that is interfering with the query.
I'm building an app using AngularJS and the MEAN Stack, and was wondering if it was possible to use the $resource factory to query a MongoDB database for a set of rows that have a certain value in one of their columns.
For example, if I wanted to build a Todo app, and I had a table with a column containing a persons username and a column with a string that had a reminder, is it possible to query the database for all the rows that have a particular username in the username column? Or, do I have to do something like this:
Todo.service.ts:
export function TodoResource($resource) {
'ngInject';
return $resource('/api/todo/:query', {
id: '#_id'
query: '';
});
}
app.js
var list = [];
this.Todo.query().$promise.then( (data) => {
for(let datum of data){
if(datum.userName == email){
list.push(datum);
}
}
});
In this sample case, I'm not really querying the database, just getting the entire table and filtering the results by myself. Is this the only way to do it, or can I directly query the database?
If you are using NODE and MongoDB, then you must be using Mongoose.
For this purpose its better to filter data on server not on client, as it would
- Decrease the amount of data on network
- Prevent unwanted data to be sent to client
Also, If you dont want to manually filter the data on server with a function, there is a function in mongoose
var query = collection.find({_id: '001'});
query.exec(function (err, results) {
if (err) {
res.json(err);
}
if (results) {
res.json(results);
}
});
this will add filter in query to mongodb before executing it, and will fetch only records having
id= 001;
i.e. filtered data
By this you will not have to filter data manually, MongoDB will handle it all.
You can send the id in the request URL
localhost:8080/collectionName/001
on NODE server:
function (req, res) {
var mainUrl = req.url.split("/");
if (mainUrl.length > 2) {
query = collection.find({_id: mainUrl[2]});
} else {
query = collection.find();
}
query.exec(function (err, results) {
if (err) {
res.json(err);
}
if (results) {
res.json(results);
}
});
}
You can also make your url like:
localhost:8080/collectionName?id='001'
then on server:
var url_parts = url.parse(req.url, true);
var queryFactors = url_parts.query;
var id= JSON.parse(queryFactors["id"]);
and use above code again for queering.
Hope this helps.
I have a select option list in Angular.js. I populate list from sql server database. It's working fine. But when I want to display data back from sql server, it doesn't work.
to populate from database (its populated)
<select ng-model="roomno" ng-options="r.Room_Name for r in rooms" value= "{{roomno}}"></select>
Now I want to show 1 particular item in that list, which is stored in database.
I tried with
$scope.roomno = response.data[0].Room_Name;
It's not working.
I would like to suggest You to use code like this:
$scope.roomno = response.data[0].Room_Name.toString();
this works fine. because somewhere stores as integer and somewhere string so need to convert as string.
How are you connecting to the server? Presumably you are using HTTP get? In which case if you want one particular room then you might want to call a separate request using the id?:
var _getRoom = function (roomId) {
return $http.get('api/Rooms/' + roomId).then(function (response) {
if (typeof response.data === 'object') {
_room = response.data;
return response.data;
} else {
return $q.reject(response.data);
}
}, function (response) {
return $q.reject(response.data);
});
};
I followed along Thinksters tutorial about firebase and angularjs
It worked great but I wanted to use the new functionality of $asArray() which required an update of angularfire (0.8).
Somehow this results in different TypeError (TypeError: undefined is not a function). For instanc on:
var query = $firebase(ref.startAt(authUser.uid).endAt(authUser.uid));
query.$on('loaded', function () { //ERROR LINE
setCurrentUser(query.$getIndex()[0]);
and
findByUsername: function (username) {
if (username) {
return users.$child(username); //ERROR LINE
}
}
I'm still able to sign in which means that i have connetction with Firebase. Does anybody have an idea of what went wrong or if I have to update anything more to get this working again?
EDIT:
my setCurrentUser-method:
function setCurrentUser (username) {
$rootScope.currentUser = User.findByUsername(username);
}
I've made an attempt to change my findByUsername-method:
findByUsername: function (username) {
if (username) {
return (users.$getRecord(username));
}
}
(relates to)
var ref = new Firebase(FIREBASE_URL + 'users');
var users = $firebase(ref).$asArray();
Still don't know a good way to search through my firebase-array correctly without .$child(username). Do I need a loop?