Recover data from within children with Angularjs - angularjs

can anybody help me? I'm having a problem similar to the previous post. I'm just not getting the child object. I have tried in several ways the most basic and logical would be: newPost.musician.statusbatera
Follows a chrome debug print: --Screen Shot--
I'm not getting it because of the key generated automatically by firebase as the print in attached.
My code:
var db = firebase.database();
var ref = db.ref("users");
ref.on("child_added", function(snapshot) {
var newPost = snapshot.val();
console.log("Musician: " + newPost.musician.statusbatera);
});

You can grab the autogenerated key using Object.keys, then you can assign the object you need:
ref.on("child_added", function(snapshot) {
var newPost = snapshot.val();
keys = Object.keys(newPost.musician)
console.log("Musician: " + newPost.musician[keys[0]].statusbatera);
});
in theory, there should be only one value in keys...

I think you want to iterate through musician's list, if so, give this a try :-
for(var i = 0; i <= newPost.musician.lenght; i++) {
console.log("Musician: " + newPost.musician[i].statusbatera);
}

Related

AWS GraphQL JSON string formatting

I'm attempting to create an object value to pass into DynamoDB using AWS AppSync and GraphQL. I'm very close to what I need but I'm stumbling on nested JSON.
Let's say I have an array:
let officers = [{"id":"0","IgRole":"Role1","IgName":"testname1","IgEmail":"testemail1","IgPhone":"testphone1","IgStart":"teststart1","IgEnd":"testend1"},
{"id":"1","IgRole":"Role2","IgName":"testname2","IgEmail":"testemail2","IgPhone":"testphone2","IgStart":"teststart2","IgEnd":"testend2"}]
I now want to create an object with each of the array values as a child object so, I do this:
for (let i in officers) {
officersJson['"' + officers[i].IgRole + '"'] = '{"Name":"' + officers[i].IgName + '","Email":"' + officers[i].IgEmail + '","Phone":"' + officers[i].IgPhone + '","Date commenced":"' + officers[i].IgStart + '","Date to end":"' + officers[i].IgEnd + '"}';
}
Here are the results:
Object {
"Role1": "{'Name':'testname1','Email':'testemail1','Phone':'testphone1','Date commenced':'teststart1','Date to end':'testend1'}",
"Role2": "{'Name':'testname2','Email':'testemail2','Phone':'testphone2','Date commenced':'teststart2','Date to end':'testend2'}"
}
I think the problem is that the each entire key / value is not in string format. If you look at
"Role1": "{......
you can see that the string breaks.
and this is the response from AWS:
Variable 'Officers' has an invalid value. Unable to parse {\"Role1\"={\"Nam
See the = sign
How can I format the object into a complete JSON string? I was fairly pleased I managed to get anywhere near the format I needed but this last bit has me stumped.
Finally worked it out. I needed a slightly different approach. Posting it in case it helps anyone else:
Firstly I created an array of roles, as this will be the keys for the value objects:
for (let i in officers) {
roles.push(officers[i].IgRole);
}
I then created a new array.
let arrOfficers = [];
for (let i in officers) {
arrOfficers.push(officers[i]);
}
I then use a function to create objects from an array:
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
let newresult = groupBy(arrOfficers, "IgRole");
Finally I create my object and then stringify it:
let officersJson = {};
for (let i in roles) {
officersJson[roles[i]] = newresult[roles[i]][0];
}
theObjectIwant = JSON.stringify(officersJson)

Cant match users in firebase

I can't randomly get user from firebase
I'm doing dating app with react native and firebase.
Users can log in with google and set their accounts, but I can't match users.
I can pick 1 user but cant display user's data.
I tried:
i tried get all users from firebase realtime database
i can pick 1 user and log user's details but cant display in app
And sometimes user.uid returns null even if i logged in.
function getRandomUser() {
const numberOfUsers = 15;
const randomIndex = Math.floor(Math.random() * numberOfUsers);
var ref = firebase.database().ref("/users/");
ref
.limitToFirst(1)
.once("value")
.then((snapshot) => {
var randomUser = snapshot.val();
console.log(randomUser);
console.log(randomUser.bio);//this is not even display in console
});
}
I believe you should change the way you are referencing your database, so it should be var ref = firebase.database().ref("users"); and not var ref = firebase.database().ref("/users/");.
After that, are some changes related to the random number number and to the comparing issues that you need to perform, so values are returned. Please, give it a try using the below code.
var dbUser = firebase.database();
var refUser = dbUser.ref("<collection>");
refUser.orderByChild("online").equalTo(1).on("value", function(Data){
var numberOfUsers = 15;
var randomIndex = Math.random() * numberOfUsers;
var userIndex = parseInt(randomIndex, 10); //parse the random number from double to integer
var currentIndex = 0;
var BreakException = {};
try
{
Data.forEach(function(snap){
if(currentIndex==userIndex){
var randomUser = snap.val();
//Do something with your random user
throw BreakException;
}
currentIndex++;
});
}
catch(e){
if(e!== BreakException) throw e;
}
While this code is untested, it was based in this successful use case here and I believe should help you. Besides that, you can get another way of returning random users, but with indexes now, by checking this similar case here, with a very complete answer from a Product Lead from Firestore.

realtime firebase database get property name and value on child_changed

I am working on real-time fire-base database.
i have a issue in getting value what is changed in fire-base.
i have client social database inside it posts and then kkkm(this is key) and then different properties and values and what i want is to toggle approval and rejected values like that approval:true but what i get is just true/false not the property name.
toggleCheck = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var approval;
ref.on("child_changed", function (data) {
approval = data.val();
console.log("=============================");
console.log("The updated approval is " + approval);
});
}
toggleClose = (id) => {
var ref = firebase.database().ref('posts/'+id);
ref.off("child_changed");
var rejected;
ref.on("child_changed", function (data) {
rejected = data.val();
console.log(ref.getKey());
console.log(ref.getValue());
console.log("=============================");
console.log("The updated rejected is " + rejected);
});
}
I'm not 100% sure to understand what you want to do ("toggle approval and rejected values"?) but, based on the code in your question, the following is probably what you are looking for:
var ref = firebase.database().ref('posts/' + id);
ref.on('child_changed', function(data) {
console.log(data.key); // <-- Name of the field/node that was modified
console.log(data.val()); // <-- Value of the field/node that was modified
console.log("The updated" + data.key + " is " + data.val());
});
Explanations:
data is a DataSnapshot which has:
A key property, which is "the key (last part of the path) of the location of this DataSnapshot."
A val() method, which "extracts a JavaScript value from a DataSnapshot."
UPDATE FOLLOWING YOUR COMMENTS
I understand that you want to get both the values of the approval and rejected nodes (fields) when something changes in the post.
Therefore you should use the value event type instead of the child_changed one, as follows:
var ref = firebase.database().ref('posts/' + id);
ref.on('value', function(data) {
var approved = data.val().approved;
var rejected = data.val().rejected;
var object = {'approved': approved, 'rejected': rejected};
//Do whatever you want with the object
console.log(object);
});

using query to read the last value and change it firebase angularjs 1

I have this database
service/
-KSxobYDhjUJeSvu3dC1
-Accion:"Nueva ronda"
-Codigo: 3
-dateTime: 1475284727
-notify: 0
-num_mesa: 0
-KSxobptdYSc-qrCSbyU
-Accion: "Orden cancelada"
-dateTime: 1475284728
-notify: 0
-num_mesa: 0
and then I have this code:
ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
var changedPost = snapshot.val();
var mykey = snapshot.key;
if(changedPost.notify == 1 ){
var message = "New action "
console.log(serviceArray[mykey].notify);//undefined
$scope.showActionToast(message);
}
});
This code will read the last entry in the database and show a toast, notifying that a new action has been inserted in firebase. It shows the toast.
My problem is that I don't want it to show every time i reload the page.
So I thought about adding a simple flag that if it was shown in a toast, it will change notify to 0.
My problem is that I have service that returns a firebaseArray named serviceArray. When I try to access the row to change the value it says undefined. How can I change the value in the same function?
You're going to be better off simply tracking the timestamp of the last message you've shown to the user. With that you can query for messages that were added after that timestamp:
var timestampOfMostRecentlySeenMessage = null;
if (timestampOfMostRecentlySeenMessage) {
ref.orderByChild("timestamp")
.startAt(timestampOfMostRecentlySeenMessage)
.limitToLast(1)
.on("child_added", function(snapshot) {
var message = snapshot.val();
timestampOfMostRecentlySeenMessage = message.dateTime;
})
Now you just need to maintain the value of timestampOfMostRecentlySeenMessage between page reloads. You could do this in a cookie, in local storage of your browser or even in a user-specific part of your database:
var userRef = firebase.database().ref("users").child(user.uid);
userRef.child("timestampOfMostRecentlySeenMessage").set(timestampOfMostRecentlySeenMessage);
i just added a flag that declares after running the search for the first time.
ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
var changedPost = snapshot.val();
var mykey = snapshot.key;
if(changedPost.notify == 1 && $scope.flag== 1 ){
var message = "New action "
console.log(serviceArray[mykey].notify);//undefined
$scope.showActionToast(message);
}
$scope.flag= 1;
});

Using AngularFire, is it possible to to create relational-style databases? Or access the UniqueIDs?

I saw this post on Firebase's blog explaining the best way to create relational data objects using their platform. I'm struggling to translate these concepts to AngularFire, their integration with the AngularJS platform.
Specifically, I'm trying to display two linked data sets that have a one way pointer reference similar to how they described it in this example from their post:
var commentsRef = new Firebase("https://awesome.firebaseio-demo.com/comments");
var linkCommentsRef = new Firebase("https://awesome.firebaseio-demo.com/links/comments");
linkCommentsRef.on("child_added", function(snap) {
commentsRef.child(snap.name()).once("value", function() {
// Render the comment on the link page.
));
});
Question: Is it possible with the current AngularFile integration to make the pointer-style references to other data objects? And if so, can you provide an example?
Edit: I feel like I'd be able to solve these problems if I can just access the unique IDs generated by AngularFire for my data [see below]. How do I access them?
Great question!
You do need access to the unique IDs, and we recently added a feature that will give you access to it via angularFireCollection: https://github.com/firebase/angularFire/pull/26.
If you're using the implicit sync method (angularFire), then you already have access to the keys as long as you specify the 4th argument that will set the type of the collection to 'Object':
function MyController($scope, angularFire) {
var url = 'https://awesome.firebaseio-demo.com/comments';
var promise = angularFire(url, $scope, 'comments', {});
promise.then(function() {
var id = '-lw2NDTiZMFvzEWmSnYn';
console.log($scope.comments[id]);
});
}
Hope this helps!
Yes you can access the ID! Use the code below!
var chru;
var ref = new Firebase("https://myapp.firebaseio.com/users/");
var sync = $firebase(ref);
var users= syncSelect.$asArray();
$scope.users= users;
users.$loaded().then(function() {
chru = users.length;
});
$scope.specificIdOnSelect = function() {
var jj;
for (jj = 0; jj < chru; jj++) {
var keyer = users.$keyAt(jj);
var rec = users.$getRecord(keyer);
if ($scope.userSelected== rec.name) {
alert("Unique Key of " + $scope.users+ " is " + users.$keyAt(jj));
}
}
};
$scope.allIds = function() {
var jj;
for (jj = 0; jj < chru; jj++) {
var keyer = users.$keyAt(jj);
var rec = users.$getRecord(keyer);
alert("Unique Key of " + $scope.users+ " is " + users.$keyAt(jj));
}
};

Resources