How to get data from Firebase database to ionic? - javascript

I am having an issue (new to JavaScript and ionic) regarding Firebase database. I have a code to display the name of a user :
.controller('accountController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
var userId = '-KcsNqRpO70spcMIPaKg';
return firebase.database().ref('/accounts/' + userId).once('value').then(function(snapshot) {
var displayName = snapshot.val().name;
$scope.$apply(function() {
$scope.displayName = displayName;
});
console.log(displayName);
// ...
});
}])
This works fine when I use directly the -KcsNqRpO70spcMIPaKg, but I would like my code to get directly this string by simply matching the logged in user to its account in the database.
I tried using var userId = firebase.auth().currentUser.uid; instead, but it doesn't grab the -KcsN..., instead it grabs the actual uid from the authentication.
I am lost. I do not understand how to grab it. Any ideas?

Alright, after searching for hours, I hope I will help a newbie just like me for this matter, the answer is to actually use "Set" instead of push and to rename your random key created by Firebase to the UID of the user :
firebase.database().ref().child('/accounts/' + user.uid).set({
name: userSignup.displayname,
email: userSignup.cusername,
password: userSignup.cpassword,
description: "No description for this user",
facebook: "",
twitter: "",
}).then(function() {
// Update successful.
$state.go("login");
}, function(error) {
// An error happened.
console.log(error);
});

Related

How do you add users and additional details to a user node in the Database every time they're registered?

I've tried to create the code by using what I've found online about adding additional details to a user node, but I've come up without a clear cut and definite solution. I can't make heads or tails with Google searches and other such things, but I only found a depreciated solution that's not supported and does not work with the current version of Firebase. So far, here's what I've come up with:
(function(){
var ref = new firebase.database();
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into Firebase so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
var ui = new firebaseui.auth.AuthUI(firebase.auth());
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
// User successfully signed in.
// Return type determines whether we continue the redirect automatically
// or whether we leave that to developer to handle.
return true;
},
uiShown: function() {
// The widget is rendered.
// Hide the loader.
document.getElementById('loader').style.display = 'none';
}
},
// Will use popup for IDP Providers sign-in flow instead of the default, redirect.
signInFlow: 'popup',
signInSuccessUrl: 'map_menu.php',
signInOptions: [
firebase.auth.EmailAuthProvider.PROVIDER_ID,
],
// Terms of service url.
tosUrl: 'map_menu.php',
// Privacy policy url.
privacyPolicyUrl: 'map_menu.php'
};
ui.start('#firebaseui-auth-container', uiConfig);
})()
You should add a code to get the user data like uid as the main child of the user and all other details as sub child nodes of this node in your database.
A Json structure that looks something like this:
{
"accounts" : {
"userId value" : {
"email" : "",
"userId" : ""
},
"userId value" : {
"email" : "",
"userId" : ""
}
}
To save the users' details in this node, just when they are registered, you can add a code like this:
var uid = firebase.auth().currentUser.uid;
firebase.database().ref().child('accounts').child(uid).set({
email: user.email,
userId: uid
})

angularjs message binding doesn't show until second form submit [duplicate]

This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 8 years ago.
I'm writing my first angularjs app, and it's beginning to make sense. However, I have a sign up form that isn't getting the messages in some cases to alert users to problems. I'm using Firebase to authenticate, which works fine. But I'm storing users by a unique username as the key. So before I run the $createUser function, I do a quick query to see if there's already a user object with this key-- if not, I create the user.
The problem is when there is an existing user with this username. The console log value prints fine, but the error message (bound to $scope.authMsg) doesn't show up the first time-- but if I click the "register" button again, then the message shows up in the expected message div.
Any hints on the message issue (or suggestions for this code) would be appreciated!
$scope.register = function() {
$scope.authMsg = '';
var ref = new Firebase(FIREBASE_URL);
$scope.authObj = $firebaseAuth(ref);
// check if the username is taken
ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
if (snapshot.val()) {
//
// PROBLEM HERE!!
//
$scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
console.log('Username exists-- did you forget your password?'); // prints to console as expected
} else {
$scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
.then(function(userData) {
console.dir(userData);
return $scope.authObj.$authWithPassword({
email: $scope.account.email,
password: $scope.account.password
});
}).then(function(authData) {
// we created a user and are now logged in-- store user info
var userdata = {};
userdata[$scope.account.username] = {
uid: authData.uid,
first_name: $scope.account.first_name,
last_name: $scope.account.last_name,
email: $scope.account.email,
full_name: $scope.account.first_name+' '+$scope.account.last_name
};
var usersRef = ref.child("users");
// save the userdata
usersRef.set(userdata);
console.log("Logged in as:", authData.uid);
$state.go('app.dashboard');
}).catch(function(error) {
$scope.authMsg = error;
console.error("Error: ", error);
});
}
}, function (errorObject) {
$scope.authMsg = 'The read failed: ' + errorObject.code;
console.log('The read failed: ' + errorObject.code);
});
};
I'm assuming, the Firebase callback does not involve an angular digest cycle.
To handle this, write
if (snapshot.val()) {
$scope.$apply(function() {
$scope.authMsg = 'Username exists— did you forget your password?';
});
A useful reading about the topic: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Using $priority with $push in AngularFire

I tried to push data to firebase using the following code and it works fine.
var firebaseObj = new Firebase("https://burning-fire-1723.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({
title: "title",
post: "post",
emailId: "mymail#gmail.com"
}).then(function(ref) {
console.log(ref);
}, function(error) {
console.log("Error:", error);
});
Next, in order to fetch a particular record from Firebase I need to assign a priority to emailId field while pushing the data.
But I really can't figure out how to do that.
Any help would be appreciated.
This should do it for you.
var user = "mymail#gmail.com";
var firebaseObj = new Firebase("https://burning-fire-1723.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({
title: title,
post: post,
emailId: user,
'.priority': user
}).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
The answer came from this this tutorial.

How do you save new users in AngularFire?

I'm trying to create users via the $createUser method which is part of the firebase simple login service.
The AngularFire/Firebase documentation discusses adding additional data to a user object -- username, etc. -- but I'm confused as to how to save the user created with $createUser to Firebase itself as
{
"users": {
"simplelogin:1": {
"provider": "password",
"email": "something#some.com"
"provider_id": "1"
},
}
}
My Firebase is currently completely empty and I'm trying to use the below controller code to create a new user.
app.controller('MainCtrl', ['$scope', '$firebase', '$firebaseSimpleLogin',
function ($scope, $firebase, $firebaseSimpleLogin) {
var ref = new Firebase('https://socialfiction.firebaseio.com/');
var sync = $firebase(ref);
$scope.auth = $firebaseSimpleLogin(ref);
var currentUser = $scope.auth.$getCurrentUser().then(function(user, err) {
if (err) {
console.log(err);
}else{
console.log(user);
return user;
}
});
$scope.createUser = function() {
$scope.auth.$createUser('jamie.smith#email.com', 'password').then(function(user) {
sync.child('users').child(user.uid).$set({
// not sure if this is right?
});
});
}
}
]);
I guess my question specifically is what do I need to add to my $scope.createUser function to properly $set the new user to a users object inside of my firebase?

AngularJS redirection after ng-click

I have a REST API that read/save data from a MongoDB database.
The application I use retrieves a form and create an object (a job) from it, then save it to the DB. After the form, I have a button which click event triggers the saving function of my controller, then redirects to another url.
Once I click on the button, I am said that the job has well been added to the DB but the application is jammed and the redirection is never called. However, if I reload my application, I can see that the new "job" has well been added to the DB. What's wrong with this ??? Thanks !
Here is my code:
Sample html(jade) code:
button.btn.btn-large.btn-primary(type='submit', ng:click="save()") Create
Controller of the angular module:
function myJobOfferListCtrl($scope, $location, myJobs) {
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(err) {
if(err)
console.log('Impossible to create new job');
else {
console.log('Ready to redirect');
$location.path('/offers');
}
});
};
}
Configuration of the angular module:
var myApp = angular.module('appProfile', ['ngResource']);
myApp.factory('myJobs',['$resource', function($resource) {
return $resource('/api/allMyPostedJobs',
{},
{
save: {
method: 'POST'
}
});
}]);
The routing in my nodejs application :
app.post('/job', pass.ensureAuthenticated, jobOffers_routes.create);
And finally the controller of my REST API:
exports.create = function(req, res) {
var user = req.user;
var job = new Job({ user: user,
title: req.body.title,
description: req.body.description,
salary: req.body.salary,
dueDate: new Date(req.body.dueDate),
category: req.body.category});
job.save(function(err) {
if(err) {
console.log(err);
res.redirect('/home');
}
else {
console.log('New job for user: ' + user.username + " has been posted."); //<--- Message displayed in the log
//res.redirect('/offers'); //<---- triggered but never render
res.send(JSON.stringify(job));
}
});
};
I finally found the solution ! The issue was somewhere 18inches behind the screen....
I modified the angular application controller like this :
$scope.save = function() {
var newJob = new myJobs($scope.job);
newJob.$save(function(job) {
if(!job) {
$log.log('Impossible to create new job');
}
else {
$window.location.href = '/offers';
}
});
};
The trick is that my REST api returned the created job as a json object, and I was dealing with it like it were an error ! So, each time I created a job object, I was returned a json object, and as it was non null, the log message was triggered and I was never redirected.
Furthermore, I now use the $window.location.href property to fully reload the page.

Categories

Resources