Adding automatically generated key in Firebase using Angular JS - angularjs

I'm currently working with Angular 1.4.5 and Firebase 4.3.0 and have some questions need to ask.
I want to know that how can I add the key which is generated automatically by Firebase into the data of particular item.
For example, by following the tutorial, I've managed to store the user ID generated by Firebase using uid
my Firebase data structure:
And this is the code
myApp.factory('Authentication', ['$rootScope', '$location', '$firebaseObject','$firebaseAuth',function($rootScope, $location, $firebaseObject, $firebaseAuth){
var ref = firebase.database().ref();
var auth = $firebaseAuth();
var myObject;
auth.$onAuthStateChanged(function(authUser){
if(authUser){
var userRef = ref.child('users').child('accounts').child(authUser.uid);
var userObj = $firebaseObject(userRef);
$rootScope.currentUser = userObj;
}else {
$rootScope.currentUser = '';
}
});
myObject = {
login: function(user){
auth.$signInWithEmailAndPassword(
user.email,
user.password
).then(function(user){
$location.path('/home');
}).catch(function(error){
$rootScope.message = error.message;
});//signInWithEmailAndPassword
},//login
logout: function(){
return auth.$signOut();
}, //logout
requireAuth: function(){
return auth.$requireSignIn();
},//require Authentication
register: function(user){
auth.$createUserWithEmailAndPassword(
user.email,
user.password
).then(function(regUser){
var regRef = ref.child('users').child('accounts').child(regUser.uid).set({
date: firebase.database.ServerValue.TIMESTAMP,
regUser: regUser.uid,
firstname: user.firstname,
lastname: user.lastname,
email: user.email
}); //userinfo
myObject.login(user);
}).catch(function(error){
$rootScope.message = error.message;
});//createUserWithEmailAndPassword
}//register
};//return
return myObject;}]);//factory
This is the code i use to add item into Firebase (function uploadItem and uploadItem1)
pageControllers.controller('UploadController',['$scope', '$firebaseAuth', '$firebaseArray',
function($scope, $firebaseAuth, $firebaseArray){
var ref = firebase.database().ref();
var auth = $firebaseAuth();
auth.$onAuthStateChanged(function(authUser){
if(authUser){
var recipesRef = ref.child('users').child('accounts').child(authUser.uid).child('recipes');
var recipesInfo = $firebaseArray(recipesRef);
var recipes1Ref = ref.child('users').child('recipes');
var recipes1Info = $firebaseArray(recipes1Ref);
var favoritesRef = ref.child('users').child('accounts').child(authUser.uid).child('favorites');
var favoritesInfo = $firebaseArray(favoritesRef);
$scope.recipes = recipesInfo;
$scope.favorites = favoritesInfo;
$scope.uploadItem = function(){
recipesInfo.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
$scope.uploadItem1 = function(){
recipes1Info.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
$scope.addFavorite = function(name){
favoritesInfo.$add({
name: name,
// name: $scope.itemName,
// index: $scope.itemIndex,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(){
$scope.message = 'Success!';
$('#Popup').modal();
console.log(name);
});//promise
}//uploadItem
$scope.deleteFavorite = function(key){
favoritesInfo.$remove(key);
} //deleteFavorite
$scope.deleteRecipe = function(key){
recipesInfo.$remove(key);
} //deleteFavorite
}//authUser
});//onAuthStateChanged}]);//myAll.controller
I want to add the key of each item into its data like putting the uid into the users data but i don't know how.

what i understand from your question is that you want to store the auto generated key from the firebase into the items that you push like below,
If you want something like this, it can be done in two ways
1 ) Pure firebase Coding
$scope.uploadItem1 = function(){
var receipeInfoKey=recipes1Ref.push().key
or var receipeInfoKey=ref.child('users').child('recipes').push().key;
var receipeInfoObj={}
receipeInfoObj= {
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP,
receipeKey:receipeInfoKey
}
recipes1Ref .child(receipeInfoKey).set(receipeInfoObj)
or
ref.child('users').child('recipes').child(receipeInfoKey).set(receipeInfoObj)
.then(function(){
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
}//uploadItem
2 ) Angular fire
// This method will be like updating the recipes1Info object after the successful push
$scope.uploadItem1 = function(){
recipes1Info.$add({
name: $scope.foodname,
category: $scope.foodcategory,
image: $scope.foodimage,
howtocook:$scope.foodhowtocook,
video:$scope.foodvideo,
date: firebase.database.ServerValue.TIMESTAMP
}).then(function(recipes1Ref){
var receipePushedObj= recipes1Info.$getRecord(recipes1Ref.key);
// recipes1Ref.key this is the auto generated key after the successful push
if(receipePushedObj!=null){
receipePushedObj.receipeKey=recipes1Ref.key;
recipes1Info.$save(receipePushedObj);
}
$scope.foodname = ' ';
$scope.category = ' ';
$scope.foodimage = ' ';
$scope.foodhowtocook = ' ';
$scope.foodvideo = ' ';
$scope.message = 'Your recipes has been uploaded successfully!!';
});//promise
here is the working sample of the first method I proposed.Js Fiddle Example

Related

Firebase angularjs firebase current auth gets replaced when creating a new user

I am working on angular firebase web app, in which as soon as admin login, he can create users by his own.
When admin log in , he is authenticated with firebase.auth()
But what is happening is, as admin creates a new user, the current auth details(admin) gets replaced by newly created user. I want the user creation without creating a newer session
Have a look at my controller:
app.controller('UserAdd', ['$scope','$sessionStorage','$http','$firebaseAuth', '$firebaseArray', '$location' ,'$firebaseObject', 'FBURL', function($scope,$sessionStorage,$http,$firebaseAuth,$firebaseArray, $location ,$firebaseObject, FBURL){
var user = firebase.database().ref().child("users");
$scope.user_auth_data = firebase.auth().currentUser;
$sessionStorage.uID = $scope.user_auth_data.uid ;
$scope.access_points= [];
$scope.teams = [];
$scope.org_details = [];
user.child($sessionStorage.uID).child("OrganizationId").on('value',function(org_id){
$sessionStorage.org_id = org_id.val();
})
user.child($sessionStorage.uID).child("ImagePath").on('value',function(img){
$scope.user_image = img.val();
})
//access points
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points").on('value',function(access_points){
angular.forEach(access_points.val(),function(ap,key){
$scope.access_points.push({id:key,ssid:ap.SSID,bssid:ap.BSSID,display_name:ap.DisplayName,lat:ap.Latitude,lng:ap.Longitude});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("access_points"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams").on('value',function(teams){
angular.forEach(teams.val(),function(team,key){
$scope.teams.push({id:key,team_name:team.TeamName,team_leader:team.TeamLeader,channel_name:team.ChannelName});
})
});
var obj = $firebaseArray(firebase.database().ref().child("organization").child($sessionStorage.org_id).child("teams"));
obj.$loaded(
function(data) {
},
function(error) {
console.error("Error:", error);
}
);
$scope.selectItem = function(){
};
//add user
$scope.addUser = function() {
firebase.auth().createUserWithEmailAndPassword($scope.Email, $scope.Password)
.then(function(user) {
//adding single values in user node
var ref = firebase.database().ref().child("users").child(user.uid);
ref.set({
EmployeeId: $scope.emp_id,
Contact: $scope.Contact,
DOB: $scope.date_of_birth,
Designation: $scope.Designation,
Email: $scope.Email,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
OrganizationId: $sessionStorage.org_id,
Gender: $scope.selectedGender,
IsAdmin: false
});
$scope.selectedAccess.forEach(function(access_values){ //adding nested access_points
var ref1 = firebase.database().ref().child("users").child(user.uid).child("AccessPoint").child(access_values.id);
ref1.set({
SSID: access_values.ssid,
BSSID: access_values.bssid,
DisplayName: access_values.display_name,
Latitude: access_values.lat,
Longitude: access_values.lng
});
});
$scope.selectedTeam.forEach(function(team_values){ //adding nested team
var ref2 = firebase.database().ref().child("users").child(user.uid).child("team").child(team_values.id);
ref2.set({
ChannelName: team_values.channel_name,
TeamName: team_values.team_name,
TeamLeader: team_values.team_leader
});
});
$scope.teams.forEach(function(team_values){
var ref3 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("channels").child(team_values.channel_name).child("info").child("users");
ref3.child(user.uid).set($scope.FirstName+" "+$scope.LastName);
var ref4 = firebase.database().ref().child("organization").child($sessionStorage.org_id).child("user_team").child(team_values.team_name).child(user.uid);
ref4.set($scope.FirstName+" "+$scope.LastName);
});
firebase.auth().sendPasswordResetEmail(user.email);
$location.path('/user_list');
}).catch(function(error) {
console.log(error);
});
};
}]);
Whats needs to be done to remain in same admin session instead of a new one?

AngularJS Firebase $add is not a function

I try to push a new record to my Firebase. But everytime I receive a console error like this:
$scope.contacts.$add is not a function
Here is my code:
app.controller('contactsCtrl',['$scope','$firebaseObject',function($scope,$firebaseObject){
var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");
$scope.contacts = $firebaseObject(ref)
$scope.addContact = function(){
$scope.contacts.$add({
name: $scope.name,
address: $scope.address,
telephone: $scope.telephone,
company: $scope.company,
email: $scope.email
}).then(function(ref){
var id = ref.key();
console.log('contact added with Id: ' + id);
});
};
}]);
You should use $firebaseArray instead of $firebaseObject
app.controller('contactsCtrl','$scope','$firebaseArray',function($scope,$firebaseArray){
var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");
$scope.contacts = $firebaseArray(ref)
$scope.addContact = function(){
$scope.contacts.$add({
name: $scope.name,
address: $scope.address,
telephone: $scope.telephone,
company: $scope.company,
email: $scope.email
}).then(function(ref){
var id = ref.key();
console.log('contact added with Id: ' + id);
});
};
}]);

Having trouble passing _id parameter in Login.controller

I'm using angular-fullstack-generator.
I'm having trouble with passing _id parameter to some function.
What I'm trying to achieve is after I created a user I want to create another Data in schema referencing to user's id
therefore here is my code
'use strict';
class SignupVendorController {
//end-non-standard
constructor(Auth, $state, $http) {
this.Auth = Auth;
this.$state = $state;
this.$http = $http;
this.submitted = false;
}
//start-non-standard
register(form) {
this.submitted = true;
if (form.$valid) {
this.Auth.createUser({
firstName: this.user.firstName,
lastName: this.user.lastName,
email: this.user.email,
password: this.user.password,
role: 'vendor'
})
.then( Auth => {
this.vendor = Auth.getCurrentUser;
this.createVendor(this.vendor._id);
console.log('user is ' + this.vendor.firstName);
console.log('vendor created');
// Account created, redirect to home
this.$state.go('main');
})
.catch(err => {
err = err.data;
this.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, (error, field) => {
form[field].$setValidity('mongoose', false);
this.errors[field] = error.message;
});
});
}
}
createVendor(id) {
var vendor = {
category: ['publishing'],
_owner: id
}
this.$http.post('/api/vendors', vendor);
}
}
angular.module('aApp')
.controller('SignupVendorController', SignupVendorController);
I've tried several syntax modification but it all just got undefined variable on this.vendor.
like this, for instance
var vendor = Auth.getCurrentUser;
console.log('the user is ' + vendor.firstName);
the code cannot read either _id or firstName.
Any kind of help would be very appreciated.
Thank you !
Can you try this?:
this.vendor = Auth.getCurrentUser();
console.log('the user_id is ' + this.vendor._id);
In my App, that's working.

Clearing input field on firebase function after angular submit

The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit. The input is tied to the var "emailInput" with ng-model. Thanks for any suggestions!
var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.emailInput = '';
};
I needed to assign a key to the email input and also an empty object.
$scope.emailInput = {};
var newEmailref = new Firebase("https://archerthedog.firebaseio.com/email");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.emailInput = {};
};
See the Full code of mine it's working for me
var ref = firebase.database().ref();
var firebasedata = $firebaseObject(ref);
var messagesRef = ref.child("storeUserData");
var data = $firebaseArray(messagesRef)
$scope.createItem= function(user) {
data.$add(user).then(function(data) {
$scope.user = "";
var myPopup = $ionicPopup.show({
title: 'Dear User, Your Account has created Successfully',
});
$timeout(function() {
myPopup.close(); //close the popup after 6 seconds for some reason
}, 6000);
});
}
ref.orderByValue().on("value", function(data) {
data.forEach(function(takenData) {
console.log("The " + takenData.key + " rating is " +
takenData.val().email);
});
});
Your code just needs a small modification to use $scope.email = ""; instead of $scope.emailInput = '';:
var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
$scope.email.$add(email);
$scope.email = '';
};
i didn't get you.... If add a item in firebase database the database will create key value,
if you doing like this
var ref = firebase.database().ref('players/');
ref.orderByValue().on("value", function(data) {
data.forEach(function(takenData) {
console.log("The " + takenData.key + " rating is " +
takenData.val().email);
});
});
The console.log answer will be for takenData.key is some id value like
(-Ko7cGuymlshrS2JQEEC)
Then takenData.val().email) is an email address...

TypeError: Cannot read property 'jsonp' of undefined

I created a function that saves data in my database.
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
$scope.movieListID = data;
console.log($scope.movieListID);
var releaseNL;
for (var i = 0; i < $scope.movieListID.releases.countries.length; i++) {
var release = $scope.movieListID.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
if(typeof releaseNL === 'undefined'){
// With release date
Notification($scope.movieListID.original_title + ' is toegevoegd, maar heeft nog geen Nederlandse premiere datum.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
} else {
Notification.success($scope.movieListID.original_title + ' is toegevoegd.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: releaseNL.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
};
} else {
console.error('Error happened while getting the movie list.')
}
})
$(".search_results").fadeOut(250);
$scope.searchquery = null
};
I want to remove this code from my controller to service. So I created a "addMovieService.js"
(function(){
"use strict";
angular.module('addMovieseat')
.factory('addMovie', [
function($http, $q, $scope){
return{
add: function(){
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
$scope.movieListID = data;
console.log($scope.movieListID);
var releaseNL;
for (var i = 0; i < $scope.movieListID.releases.countries.length; i++) {
var release = $scope.movieListID.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
if(typeof releaseNL === 'undefined'){
// With release date
Notification($scope.movieListID.original_title + ' is toegevoegd, maar heeft nog geen Nederlandse premiere datum.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
} else {
Notification.success($scope.movieListID.original_title + ' is toegevoegd.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: releaseNL.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
};
} else {
console.error('Error happened while getting the movie list.')
}
})
$(".search_results").fadeOut(250);
$scope.searchquery = null
}
}
}])
})();
And in my controller I now have,
$scope.addMovie = function() {
addMovie.add();
};
Now when I fire the addMovie function I get an error TypeError: Cannot read property 'jsonp' of undefined. Can someone explain what´s going wrong?
You're not injecting $http properly. You're using an array as the second argument in factory(...), but you're not giving it the names of the injected fields.
Possible fix:
angular.module('addMovieseat').factory('addMovie', ['$http', '$q',
function($http, $q) {...}]);
EDIT: I removed $scope since it can't be injected into factories.

Resources