Returning newly created key after .push firebase - angularjs

I'm new to Firebase but I need to update a prop 60 seconds after it is pushed to Firebase. How can get the dynamic key Firebase creates after a .push() is successful?
function storeData(val){
$scope.ref = new Firebase('...')
$scope.ref.push({'va1': val, 'status': 'active' });
//after push give me back the newly created key string for that item only
}

Pass the key property at the end of push().
function storeData(val){
const dataRef = new Firebase('...')
const key = dataRef.push({'va1': val, 'status': 'active' }).key;
}
// Before returning the key value, it pushes the data to the database.

I figured it out. I found this worked like a charm
$scope.ref.limitToLast(1).on("child_added", function(snapshot) {
console.log(snapshot.key());
})

Related

How can i pop a value with key from local state?

I have a local state as object:
selectedDates = {};
When i click on icons I am getting ID´s in my local state as object key, value pair.
// We "open" the value to extract the relevant informations
const [key, value] = calendarIconId.split("=");
// Add the new value inside of the object
this.state.selectedDatesTemp[key] = value;
// Turn the object into an array, we gotta rebuild the values
const date = Object.keys(this.state.selectedDatesTemp).map(
x => `${x}=${this.state.selectedDatesTemp[x]}`
);
How can i delete an object from the local state?
You can use delete to achieve it:
const { selectedDatesTemp } = this.state;
delete selectedDatesTemp[key];

Why can't I update its element value correctly within Array.forEach() loop in Angular 7?

I'm testing Material Table(mat-table) on Angular 7, here's a weird issue I ran into.
Send a request to jsonplaceholder for fake data in users.service
export class UsersService {
API_BASE = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) {}
getUsers(): Observable<object> {
const url = this.API_BASE;
return this.http.get(url);
}
}
Because jsonplaceholder only returns 10 rows of data, so I concatenate the data for a larger array, say, 30 rows for testing pagination feature with ease. Meanwhile, update the 'id' field with iterate index so the 'id's looks like 1,2,3...30, instead of 1,2,3...10,1,2,3...10,1,2,3...10, which is a result of concatenation, that's it, nothing special.
users.component:
ngOnInit(): void {
this.userService.getUsers().subscribe((users: UserData[]) => {
users = users.concat(users, users);
users.forEach((user, index) => (user.id = index +1));
console.log(users);
this.dataSource.data = users;
});
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
Although the table shows up beautifully, but the 'id's column looks weird, they are not 1,2,3...30 sequentially, instead, they are 21,22,23...30,21,22,23...30,21,22,23...30
I tried to print out the user.id inside the forEach loop, it's all good.
users.forEach((user, index) => {
user.id = index + 1;
console.log(user.id);
});
Where did I go wrong with this? Any clue? Thanks.
P.S, API used in the code: https://jsonplaceholder.typicode.com/users
even though you have 30 array elements after concatenating the array twice, you still only have 10 unique objects. the Object behind users[20] is the same as users[0], so you override the id of the already processed objects from index 10 to 29
you can fix this by creating a copy of each object. There are many ways too do this. a very simple way is serializing and deserializing using JSON.stringify and JSON.parse:
users.forEach(user => users.push(JSON.parse(JSON.stringify(user))));

how to retrieve parent's value based on child

I am trying to retrieve the user's key based on the child's email, which is student#memail.com in this case. I have tried many ways but could not get a way to retrieve the key of the record. I want to retrieve the value KKTxEMxrAYVSdtr0K1NH , below is the snapshot of the database
Currently, if((childSnap.val().role) == "student") { returns me student and snap.key() returns me "User". How do I retrieve KTxEMxrAYVSdtr0K1NH ?
What method are you using to retrieve the node? If you are using on "child_added" then you can use: childSnap.key
If you are using on "value" then your references is the keys in the response object. So you can use:
for (var key in childSnap.val()) {
console.log(key)
}
or
childSnap.forEach(...)
Here is an example to clearify (check the console):
https://jsfiddle.net/qrLvbok4/1/
There is a difference between value and child_added, check the list for child events section: https://firebase.google.com/docs/database/web/lists-of-data
var ref = firebase.database().ref('Users');
ref.on('child_added', function(snap) {
// You can retrieve the parent key by calling snap.key
console.log(snap.key);
});
UPDATE (Get parent key by email):
var ref = firebase.database().ref('Users').orderByChild('email').startAt('student#memail.com').endAt('student#memail.com');
ref.once('value', function(snap) {
console.log(Object.keys(snap.val())[0]);
});

Auto-adding new item - Angular UI query

I'm adding a 'new stories' feature to a website for authors to contribute work to. The function below allows stories to be created and added to the author's profile but doesn't auto-add them to a list (ie I have to refresh the browser for this to work. Does anyone know if there is a way to do this (I've tried changing state back to 'authorprofile' but that didn't work).
self.addStory = function() {
var authorId = tokenService.getAuthor()._id;
console.log(authorId);
var data = {
story: self.currentStory,
authorId: authorId
}
Story.save(data, function(story) {
console.log("saving: " + story);
Story.put(data, function(story){
console.log("story added");
})
// auto-add new stories here
$state.go('authorprofile');
})
}
Assuming the list of stories is stored in a 'stories' variable on the scope:
// auto-add new stories here
$scope.stories.push(data);
Add new story into the array using in the success function using push method.
Story.save(data, function(story) {
//Add stories to the array
$scope.stories.push(story);
Story.put(data, function(story){
console.log("story added");
})
// auto-add new stories here
$state.go('authorprofile');
})

Backbone.js — url :id not getting passed to where loop

I have this code in my router:
category: (id) ->
alert id
filteredProducts = new App.Collections.Products(#productsCollection.where({category_id: id}))
#productsView.renderResults(filteredProducts)
The alert id call works properly (e.g. app.com/categories/6 > alerts "6") and when I change the id in the where function to an actual number the products collection filters properly like so:
filteredProducts = new App.Collections.Products(#productsCollection.where({designer_id: 6}))
But when I set the designer_id: id the where loop return an empty collection.
My foreign key category_id was a number not a string. The answer is:
filteredProducts = new App.Collections.Products(#productsCollection.where({category_id: parseInt(id)}))

Resources