Querying Firebase based on time - angularjs

I am trying to query my Firebase based on time limits. I am following this blog post with this attached jsFiddle.
The issue is that I am getting a blank firebaseArray back.
var currentTime = (new Date).getTime();
var twentyFoursHoursAgo = currentTime - 86400000;
//scoresRef is defined as new Firebase(http://myfirebase.firebaseio.com/scores)
scoresRef.on('value', function (dataSnapshot) {
var summaryScores = $firebaseArray(scoresRef.orderByChild('timestamp').startAt(twentyFoursHoursAgo).endAt(currentTime));
$scope.summaryScores = summaryScores;
console.log(summaryScores);
}
The idea is that as users add more scores, the array will change. Then I can do different data manipulation on it (like average, etc). That way, there can be a running 24 hour average displayed on the app.
This is what the data looks like in Firebase:
What am I doing wrong? I know the data is in there.

Not sure if this answer your question, but it seems the best I can do is show you something that works.
Querying for a range of timestamps
I added this data structure:
{
"-Jy5pXbn5RpiK1-5z07O": {
"timestamp": 1441076226561
},
"-Jy5pZJsYvsmv_dMtCtn": {
"timestamp": 1441076173543
},
"-Jy5paWbkU6F8C6CEGpj": {
"timestamp": 1441076181550
},
"-Jy5pbc0pJ1I5azenAi5": {
"timestamp": 1441076247056
},
"-Jy5pfnMDKExW2oPf-D-": {
"timestamp": 1441076204166
},
"-Jy5pgk55ypuG9_xICq-": {
"timestamp": 1441076268053
},
"-Jy5phVgU2hDE_izcR8p": {
"timestamp": 1441076271163
},
"-Jy5pilBteGhu05eMWQI": {
"timestamp": 1441076215315
}
}
And then query with this code:
var ref = new Firebase('https://stackoverflow.firebaseio.com/32321406');
var startAt = 1441076265715;
var endAt = startAt + 15000;
var query = ref.orderByChild('timestamp')
.startAt(startAt)
.endAt(endAt);
query.on('value', function(snapshot) {
console.log(snapshot.val());
});
Which outputs:
{
-Jy5pgk55ypuG9_xICq-: {
timestamp: 1441076268053
},
-Jy5phVgU2hDE_izcR8p: {
timestamp: 1441076271163
}
}
And a warning that I should add an indexing rule for timestamp.
jsbin: http://jsbin.com/qaxosisuha/edit?js,console
Binding a collection of data from Firebase to AngularJS
If you're trying to bind the query results to an AngularJS view, you do this by:
$scope.items = $firebaseArray(query);
When using AngularFire don't try to use console.log to monitor what is going in. Instead add this to your HTML:
<pre>{{ items | json }}</pre>
This will print the items and automatically update as the data is asynchronously loaded and updated.
Note that this may be a good time to go through Firebase's AngularFire programming guide, which explains this last bit and many more topics in a pretty easy to follow manner.

Related

AngularJS - Calling values in response with Spring GET

New here so my description might be bad but I'm trying to access the values on the second level of my JSON but I can't seem to get it. It only brings the values of the top level.
My JSON body looks like the following:
{
"services": [
{
"nameLevel1": "Example1",
"secondServices": [
{
"id": 1,
"namelevel2": "Example2",
}
]
}
]
}
And when I call it, I only can get the nameLevel1 and that is it. My GET method is this:
$scope.retrieveServices = function (id) {
SpringDataRestService.get(
{
"collection": "user",
"resource": id
},
function (response) { // Success Function
$scope.userServices = response.services;
$scope.recievedValues = true;
}
);
};
Now I originally thought all I would have to do is:
$scope.userServices = response.services.secondServices;
But I'm getting an undefined issue. So my query is how do I access all of them? My JSON body when doing a log output does show everything, but for some reason I can't seem to get it to show everything in my table. Only the nameLevel1 values.
Any help would be appreciate, and I hope my description is okay. Edits would be get as well since not too sure if I have labelled this correctly. Thank you!

equalTo returning null from Firebase?

In my React Native App, I currently am trying to pull all items that have the selected property set to "true" from the database. However, when I log the results of this query, they are all being returned as null (even though expected response should be returning two objects). My relevant code as well as Firebase structure are included below, please let me know if you spot anything.
const rootRef = new Firebase(`${ config.FIREBASE_ROOT }`)
var queryRef = rootRef.orderByChild("items/selected");
var solution = queryRef.equalTo("true").once('value', function(snap) {
console.log(snap.val())
});
Firebase JSON:
"items":
[
{
"title":"ball",
"selected": "false"
},
{
"title":"dog",
"selected": "true"
},
{
"title":"phone",
"selected": "false"
},
{
"title":"cup",
"selected": "true"
}
],
When you run an Firebase query on a location, it takes each child node under that location and then evaluates the condition you specify. If you take each child under items, you'll see there is no path items/selected under there.
You query is instead:
var itemsRef = rootRef.child("items");
var queryRef = itemsRef.orderByChild("selected");
You should use
where("selected" = true)
instead of equalTo()

Query data from firebase Array

My firebase users tree has this structure:
users:
{
{
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences':
[
0:'Cinema',
1:'It'
]
},
{
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences':
[
0:'Cinema',
1:'Music'
]
}
}
Then, I try to find all users that their preference list contain 'Cinema'.
I try this code:
var ref1 = new Firebase("https://event-application.firebaseio.com/users");
$scope.user = $firebaseArray(ref1.orderByChild("userpreferences").equalTo('Cinema'));
console.log($scope.user);
But I don't get the best result. I get this record:
Your JSON structure shows preferences as userPreferences, so wouldn't the following work?
var ref1 = new Firebase("https://event-application.firebaseio.com/users");
$scope.user = $firebaseArray(ref1.orderByChild("userPreferences").equalTo('Cinema'));
console.log($scope.user);
However I think there is also another problem with your code, you're called an .equalTo('Cinema') however you're comparing it to an array, correct me if i'm wrong but I don't think the behaviour of .equalTo('Cinema') is to loop through each of the values and compare them, I think it's just a straight up comparison
If this is the case, you may need to build a custom query by reading the data from firebase and manipulating it via function available to a snapshot
In NoSQL you'll often end up with a data model that reflects the way your application uses the data. If you want to read all the users that have a preference for Cinema, you should model that in your tree:
users: {
'uid-of-abc': {
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences': [
0:'Cinema',
1:'It'
]
},
'uid-of-def': {
'userName': 'def',
'userEmail' : 'abc#abc.com',
'userPreferences': [
0:'Cinema',
1:'Music'
]
}
},
"preferences-lookup": {
"Cinema": {
"uid-of-abc": true,
"uid-of-def": true
},
"It": {
"uid-of-abc": true
},
"Music": {
"uid-of-def": true
}
}
Now you can find out what users prefer cinema with:
ref.child('preferences-lookup/Cinema').on('value', function(snapshot) {
snapshot.forEach(function(userKey) {
console.log(userKey.key()+' prefers Cinema');
});
});
This is covered in this blog post on denormalizing data with Firebase, in the Firebase documentation on structuring data and in dozens of answers here on Stack Overflow. A few:
Storing Relational "Type" or "Category" Data in Firebase Without the Need to Update Multiple Locations
Get Firebase items belonging to category
Retrieve data based on categories in Firebase
How to query firebase for property with specific value inside all children

$q.all(promises)and structure of promises object to collect the returned data

I am using Angularjs $q.all(promises) to make multiple REST call and then collecting the data once promise is successful. I have following following.
If "promises is simple array then it works Plunker
var promises = [
Users.query().$promise,
Repositories.query().$promise
];
If "promises" is simple object then also it works Plunker
var promises = {
users: Users.query().$promise,
repos: Repositories.query().$promise
};
If "promises" is nested object then it is not working. For my requirement I need nested object to remember the input parameters. Plunker
var promises = {
users: {"phx":Users.query().$promise},
repos: {"phx":Repositories.query().$promise}
};
These plunkr are just to simulate my problem. However I want this approach in real project for following requirement.
I have list of 12 product
Each product has "details", "benefits" and "offers" data
I have separate REST API services for "details", "benefits" and "offers" having :productID as parameter
I am making call in following order
a. Loop for each cards
b. For each card, make a REST API call for "details", "benefits" and "offers"
c. Add #b steps into "promises" object
d. call
$q.all(promises).then(function(results) {
// Here need logic to compile the result back to product
// and corresponding "details", "benefits" and "offers" mapping
}
and get the data back
Following is json structure I needed to collect my response.
{
"prod1": {
"benefits": {},
"offers": {},
"pages": {
"productPage": {}
}
}
},
"common": {
"benefits": {},
"pages": {
"commonBenefit": {}
},
"others": {}
}
How can I achieve this?
If you really need it, you can wrap the nest with $q.all like this:
var promises = {
users: $q.all({"phx": Users.query().$promise}),
repos: $q.all({"phx": Repositories.query().$promise})
};
plnkr.co

Trouble with updating object properties in AngularJs

I am building my first app in AngularJs.
Here is the plunkr with what I've done so far. The user should be able to add new websites and group them in groups. Groups are also made by the user. Any time the new group is created it is available for new websites. What app should also do is to update group objects with newly assigned websites... and this is where I fail.
Here is how json should look like:
{
"sites": [
{
"url": "http://sfdg",
"id": 0,
"groups": [
{
"name": "adsf",
"id": 0
}
]
}
],
"groups": [
{
"name": "adsf",
"id": 0,
"sites": [//sites assigned
]
}
]
}
In the plunkr code I used push but that just adds new group...
Could you please direct me to the right way of achieving this.
Thanks!
To prevent circular references (a website object refers to a group object that refers to the website object, etc...), I would store id's to the relevant objects instead.
First, when creating a new group, add an empty sites array to it:
function createGroup(newGroup) {
newGroup.sites = []; // <-- add empty array of sites
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
Then, when you create a new site, update each group to which the site is added:
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
sitesMap[newSite.id] = newSite;
// instead of storing the groups array, only store their id:
newSite.groups = groups.map(function(group) { return group.id });
// and add this new sites id to the groups' sites array.
groups.forEach(function(group) {
group.sites.push(newSite.id);
});
siteIdSeq++;
return newSite;
}
(updated plunker here)

Resources