How do you save new users in AngularFire? - javascript

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?

Related

Saving data for only one user with using Firebase

I'm developing electron app and using Firebase Database. I created database user by user but saving data for everyone. I want to save data also separate for the user ID.
I can create a user under their user IDs but cannot write their data under their user IDs.
app.controller('loginCtrl', function($scope,$location){
$scope.signup = function(){
auth.createUserWithEmailAndPassword($scope.mail,$scope.parola).then(sonuc=>{
console.log(sonuc.user);
return db.collection('users').doc(sonuc.user.uid).set({
inputQ: $scope.inputQ
}).then( ()=> {
console.log('deneme basarili');
}).catch(err => {
console.log(err.message);
})
})
}
$scope.login = function(){
auth.signInWithEmailAndPassword($scope.mail,$scope.parola).then(sonuc=> {
$location.path('/dashboard')
})
}
});
This part successfully creates a user under its user ID.
app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).add({
baslik: $scope.baslik,
icerik: $scope.icerik
}).then( ()=> {
console.log('ekleme basarili');
}).catch(err=>{
console.log(err.message);
})
}
This part cannot create data under its user ID.
The error is user is not defined.
app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).set({
baslik: $scope.baslik,
icerik: $scope.icerik
}).then( ()=> {
console.log('ekleme basarili');
}).catch(err=>{
console.log(err.message);
})
}
Trying using "set" rather than "add", "add" is usually reserved for adding to a collection where it creates the records identifier for you, without you having to provide it.
You should change .add to .set but also make sure to include merge: true to prevent an override to the document (e.x. if there is a current document it will update it and if there is no document it will create one).
app.controller('dashboardCtrl', function($scope){
$scope.add = function() {
db.collection('users').doc(user.uid).set(
{
.
.
.
},
{ merge: true }
).then( ()=> {
}).catch(err=>{
})
}

Angular js Web Application failed to Return Expected Message

I am consuming WCF Rest Service into Angular js web application. First I am checking username in database . If the username name is exist then i want to display message in angular js web application is username name is exist please choose other username .If username is not exist then i want to insert the record into database .But the problem is its not displaying message username is not displaying expected message and i got following error .
The server encountered an error processing the request. The exception message is 'Non-static method requires a target.'. See server logs for more details. The exception stack trace is:
Here is the Method.
public bool RegisterUserEncryptPassword(tblUser user)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var query = (from x in context.tblUsers
where x.Username == user.Username
select x).SingleOrDefault();
if (query != null)
{
return true;
}
else
{
tblUser createUser = new tblUser();
createUser.Username = user.Username;
createUser.Password = Utility.Encrypt(user.Password);
createUser.Email = user.Email;
ctx.tblUsers.Add(createUser);
ctx.SaveChanges();
}
}
return false;
}
Here is my script code..
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
$scope.createuser = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
Email: $scope.Email
};
if ($scope.OperType === 1) {
var promisePost = myService.post(User);
promisePost.then(function (pl) {
$scope.Id = pl.data.Id;
window.location.href = "/Login/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect or username is exit !";**//Always Hit on This line**
console.log("Some error Occured" + err);
});
}
}]);
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/RegisterUserEncryptPassword",
data: JSON.stringify(User)
});
return request;
};
})
Here is the Screen shot when i run the application.When i try to insert new record i i want to display
here is error message in network tab.
You need to bind the #scope.msg into an html element like label or span. This html element must be loaded inside the DOM with hidden status. You have to just show it with ng-show.

How to get data from Firebase database to ionic?

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);
});

AngularJS tutorial Thinkster.io chapter 7

UPDATE: The tutorial was updated and the following question really no longer applies
Learning about AngularJS from the site thinkster.io (free ebook). But at the moment i'm stuck at chapter 7 - Creating your own user data using firebase. This is an tutorial about angularjs that works with firebase.
I have wrote all the code according to the site, but i'm getting these console errors when I want to register a user. It will create the user (in firebase -simplelogin), but not the user object (in firebase - data).:
TypeError: undefined is not a function
at Object.User.create (http://localhost:9000/scripts/services/user.js:46:19)
at http://localhost:9000/scripts/controllers/auth.js:32:22
etc.
This is the code (same as the site), the error is in the create() function and talks about the users.$save() function, snippet of User.create():
users.$save(username).then(function () {
setCurrentUser(username);
});
Complete code of user.js:
news.factory("User", function ($firebase, FIREBASE_URL, $rootScope, $log) {
var reference, users, User;
reference = new Firebase(FIREBASE_URL + "users");
users = $firebase(reference);
function setCurrentUser(username) {
$rootScope.currentUser = User.findByUsername(username);
}
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference.startAt(authUser.uid).endAt(authUser.uid));
query.$on("loaded", function () {
setCurrentUser(query.$getIndex()[0]);
});
});
$rootScope.$on("$firebaseSimpleLogin:logout", function () {
delete $rootScope.currentUser;
});
User = {
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
"$priority": authUser.uid
};
$log.debug(users);
users.$save(username).then(function () {
setCurrentUser(username);
});
},
findByUsername: function (username) {
if (username) {
return users.$child(username);
}
},
getCurrent: function () {
return $rootScope.currentUser;
},
signedIn: function () {
return $rootScope.currentUser !== undefined;
}
};
return User;
});
Edit 1:
Registering a user now works, got it working (saving in firebase, simple login and data):
users = $firebase(reference).$asObject();
Notice the users.save() function:
create: function (authUser, username) {
users[username] = {
md5_hash: authUser.md5_hash,
username: username,
$priority: authUser.uid
};
$log.debug(users);
users.$save().then(function () {
setCurrentUser(users);
});
},
findByUsername: function (users) {
if (users) {
return users;
}
},
Edit 2:
Now I get an error at the log in of the user (see below), when I want to log in, I get an error on this this function, query.$on():
TypeError: undefined is not a function
at http://localhost:9000/scripts/services/user.js:26:19
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference.startAt(authUser.uid).endAt(authUser.uid));
query.$on("loaded", function () {
setCurrentUser(query.$getIndex()[0]);
});
});
What is wrong now?
This is an answer on edit 2: I have used firebase(ref), query.$loaded and searched for the right object, that's it. Maybe someone have an different answer, please post them :).
I have finally completed chapter 07!
In general (solution for Edit 2):
$rootScope.$on("$firebaseSimpleLogin:login", function (event, authUser) {
var query = $firebase(reference).$asObject();
query.$loaded(function (result) {
angular.forEach(result, function (key) {
if (key.md5_hash === authUser.md5_hash) {
setCurrentUser(key);
}
});
});
});
This is not the ideal solution, but the free ebook (atm of writing) is far from ideal. Then again, these kind of situations helps you to understand a little bit more about the firebase api and how it works with angular. But can be frustrated at times, when you just want to go through the tutorial ;).
Note! I have saved the User object and pass the User object to the findUsername() and setCurrentUser() functions instead of just the user.username.
You can also use the native array function, like some().
I think your system uses the newer version of Angularfire (version>= 0.8). Which means for running through loops that are arrays ...you need to attach .$asArray() at the end of the user definition field. Check the updates of 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