angularfire $add not working - angularjs

I'm trying to do a simple CRUD with ionic (v1) and angularfire. I can read and delete records but I need to edit and create. The actual problem is angularfire function $add`, this function doesn't do anything and doesn't return any error in the console. I have this code:
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
username: $scope.user.username,
email: $scope.user.email,
street: $scope.user.street,
suite: $scope.user.suite,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
phone: $scope.user.phone,
website: $scope.user.website,
}
console.log(data);
$scope.users.$add(data).then(function (ref) {
console.log('contact added with Id: ' + id);;
})
Apparently the code is fine, but doesn't return console.log so maybe had some errors. Any ideas?

Well to find out if there is any error Javascript then takes to call back one for success and the other for failure something like the code below
$scope.user.$add(data).then(function (success){
return console.log(success);
}, function(error){
return console.log(error);
})
Now that's for then that way you can log returned errors

Error fixed.
$scope.users = $firebaseArray(root.ref('/users/'));
$scope.user = {};
//Create
$scope.title = "New user"
$scope.button = "Create";
$scope.icon = "ion-person-add";
$scope.submit = function () {
var data = {
name: $scope.user.name,
phone: $scope.user.phone,
email: $scope.user.email,
username: $scope.user.username,
city: $scope.user.city,
lat: $scope.user.lat,
lng: $scope.user.lng,
street: $scope.user.street,
suite: $scope.user.suite,
website: $scope.user.website,
zipcode: $scope.user.zipcode,
}
$scope.users.$add(data).then(function (response) {
if (response) {
$ionicPopup.alert({
title: '<div><i class="ion-checkmark-circled"></i></div>',
subTitle: '<h4>The user <b>' + data.name + '</b> is added.</h4>',
});
}
$scope.user=null;
With that all works properly and modal shows when we add user.

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

update/refresh angularjs ng-repeat with data from server

I try to buil a website to like some pictures.
I can load the picture, but I want to have a like system with who like the picture.
my problem was I have to refresh the page to see who like this picture and increment the count.
this my controller :
$scope.loadingpics = function (){
$http.get('/api/photos')
.success(function(awesomeThings) {
console.log(awesomeThings);
$scope.firstname = awesomeThings;
})
.error(function (err){
$scope.errors.other = err.message;
});
};
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
var num = index.vote + 1;
$http.put('api/photos/' + nom, {
email: email,
vote: num
})
.success(function (data) {
$scope.firstname = data;
$scope.loadingpics();
})
.error(function (err){
$scope.errors.other = err.message;
});
};
this is my view :
<li ng-repeat="image in firstname | orderBy: 'firstname'" ng-show="isLoggedIn()" class="thumbnail" title="Image 1" on-last-repeat>
<img ng-src="../assets/images/Pouce.png" ng-click="upVote(image)" data-toggle="popover" data-content="And here's some amazing content. It's very engaging. Right?" data-placement="right" title="Popover title">
</li>
this is my schema :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: Number,
active: Boolean
});
Thanks for your help :D
Instead of storing only the number of likes in your schema, store an array of object :
var PhotoSchema = new Schema({
url: String,
firstname: String,
email: [String],
info: String,
vote: [{
date: Date,
user: String
}],
active: Boolean
});
I just change my upVote function by adding a $scope.watch and $scope apply.
This is my example :
$scope.upVote = function(index){
$scope.vote = 1;
var ref = index;
var nom = index.url.substr(30, 40);
console.log(nom);
console.log(index.vote);
var num = index.vote + 1;
console.log(index);
$http.put('api/photos/' + nom, {
email: email,
})
.success(function (data) {
$scope.firstname = data;
})
.error(function (err){
$scope.errors.other = err.message;
});
$scope.$watch($scope.firstname, $scope.loadingpics());
$scope.apply();
};

Getting and Setting a Factory value/object in AngularJS

Part of this is includes the question of whether or not this is possible, but I am trying to make a factory value called currentUser, which will hold a single use from userService. I am trying to figure out how to make this interaction occur.
If my factories are as follows:
app.factory('currentUser', function() {
});
app.factory('userService', function() {
return {
users: [{
name: "John",
password: "12",
email: "test#example.com",
phone: "238-491-2138"
}, {
name: "Austin",
password: "potaoes",
email: "example#gmail.com",
phone: "138-490-1251"
}]
};
});
and I have a controller that does the following, is there a way to put currentuser = userService.users[i];. Or if this is a terrible way of doing it, how might I setup a way to keep track of a "current user"?
$scope.login = function() {
for (var i = 0; i < userService.users.length; i++) {
if (userService.users[i].email.toLowerCase() === $scope.credentials.email.toLowerCase()) {
if (userService.users[i].password === $scope.credentials.password) {
$scope.messageLogin = "Success!";
$timeout(function() {
$timeout(function() {
$location.path("/account");
}, 500)
$scope.loggedIn = true;
$scope.messageLogin = "Redirecting...";
// currentUser == userService.users[i];
}, 500)
} else {
$scope.messageLogin = "Incorrect login details";
}
return;
}
}
$scope.messageLogin = "Username does not exist";
};
Not sure if this is possible due to the fact that the factory seems to always have a return and never a get/set scenario. So if this is a bad use for Factory, how should I go about it?
You have a couple of options. You can make it part of the user service itself:
app.factory('userService', function() {
var currentUser;
return {
getCurrentUser: function() {
return currentUser;
},
setCurrentUser: function(user) {
currentUser = user;
},
users: [{
name: "John",
password: "12",
email: "test#example.com",
phone: "238-491-2138"
}, {
name: "Austin",
password: "potaoes",
email: "example#gmail.com",
phone: "138-490-1251"
}]
};
});
or you can store it in a separate object:
app.factory('currentUser', function() {
var currentUser;
return {
getCurrentUser: function() {
return currentUser;
},
setCurrentUser: function(user) {
currentUser = user;
}
};
});
Services/Factories in AngularJS are singletons, so you should build your application with the expectation that a service will always resolve to the same value.
That being said, your service is just a JavaScript object and its fields/properties are mutable. I don't see anything wrong with adding a field called "current" to your "userService", which is designed to contain a reference to the current user.

AngularJS-MongoLab $resource update error

I am connecting AngularJS with MongoLab and trying to update the "users" collection.
AngularJS resource service:
angular.module("myApp.services", ["ngResource"])
.constant({
DB_URL: "https://api.mongolab.com/api/1/databases/mydb/collections/users/:id",
API_KEY: "[SOME_RANDOM_KEY]"
})
.factory("UsersService", ["$resource", "DB_URL", "API_KEY", function($resource, DB_URL, API_KEY) {
return $resource(DB_URL, { apiKey: API_KEY, id: "#_id.$oid" }, { update: { method: "PUT" }});
}]);
This is how I am trying to update my users collection:
angular.module("myApp", ["myApp.services"])
.controller("AppController", ["$scope", "UsersService", function($scope, UsersService) {
$scope.users = [];
$scope.getAllUsers = function() {
$scope.users = UsersService.query();
};
$scope.updateUser = function(user) { // user: firstName, lastName, email
//delete user._id;
UsersService.update({}, user, function() {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function() {
console.log("Some problems updating the user", arguments);
});
};
}]);
When I try to update the user information, it throws an exception stating:
{ "message" : "cannot change _id of a document old:{ _id: ObjectId('[SOME_RANDOM_KEY]'), firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#emal.com\" } new:{ _id: {}, firstName: \"Anup\", lastName: \"Vasudeva\", email: \"anup.vasudeva#email.com\" }"
I am new to MongoDB, so I don't understand why it is creating an empty _id object for the new user instance?
Try changing your $scope.updateUser function to the following:
$scope.updateUser = function (user) {
var userId = user._id.$oid;
user._id = undefined;
UsersService.update({id: userId}, user, function () {
$scope.users = UsersService.query();
console.log("Users updated successfully");
}, function () {
console.log("Some problems updating the user", arguments);
});
};
The update/replacement object ('user'), should not contain the _id property when being passed to UsersService.update(). Mongo will not replace the _id value, so the id will stay the same after the update.
One other thing that's changed in this function is that we're passing the user id as the first parameter of the UsersService.update() function so that mongo knows which document to update.

Resources