I am sooo close I can smell the finish line --
When my app starts, I harvest the login information from the user (it's an AngularJS SPA so I can get it easy from spInfoContext) and I check to see if the user is a returning user by searching a list called itiUsers for the userId. If no records are found, I immediately create a new record in itiUsers and then present a form for the new user to enter the information that I can't grab from SharePoint. The record is created properly. When the promise returns, I am trying to populate the $scope.current_user object so that it would be the same as if this were a returning user -- that's so I only have to have one My Preferences form.
However when I log out $scope after the record is created, current_user is empty.
Here's my Controller function (i reduced values for brevity and I tried to bold the problem line):
$.when(SharePointJSOMService.getCurrentUser())
.done(function(jsonObject){
if(jsonObject.d.results.length < 1 || jsonObject.d.results.newUser ){
// new user
$.when(SharePointJSOMService.getLoggedInUser())
.done(function(jsonObject){
$scope.loggedInUser = jsonObject.d;
$scope.isNewUser = true;
$.when(SharePointJSOMService.createNewUser($scope))
.done(function(jsonObject){
**$scope.current_user.DisplayName = $scope.loggedInUser.Title;
console.log($scope);**
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
$scope.prefPane = true; // force preference pane
$scope.taskClose = true;
$scope.$apply();
} else {
// existing user
$scope.isNewUser = false;
$scope.prefPane = false; // hide preference pane
$scope.current_user = jsonObject.d.results[0];
switch($scope.current_user.Role){
case 'USR':
$scope.projectClose = 'true';
break;
case 'PMG':
$scope.projectClose = 'false';
break;
default:
$scope.projectClose = 'true';
break;
} // end switch
$scope.$apply();
} // end if
})
.fail(function(err){
$scope.prefPane = true;
console.info(JSON.stringify(err));
});
It crashes because you are trying to set $scope.current_user.DisplayName after creating a new user but $scope.current_user object is undefined. Try instead:
$scope.current_user = {
DisplayName: $scope.loggedInUser.Title
}
Related
I was working with this project, it is linked to mongodb, it was working perfectly, so I could register new users, edit and save them. I format my laptop, then I cloned my project but it doesn't work anymore, when I try to register a new user it gives me the error: "NEXT IS NOT A FUNCTION", I haven't modified anything. I don't know really what happened. I have tried it in a different laptop and it works. So I have to keep working on it but I can't because of it.
I leave some code in case if it is something wrong.
Thanks!
server.js
var express = require("express"); // ExperssJS Framework
var app = express(); // Invoke express to variable for use in application
var port = process.env.PORT || 5555; // Set default port or assign a port in enviornment
var morgan = require("morgan"); // Import Morgan Package
var mongoose = require("mongoose"); // HTTP request logger middleware for Node.js
var bodyParser = require("body-parser"); // Node.js body parsing middleware. Parses incoming request bodies in a middleware before your handlers, available under req.body.
var router = express.Router(); // Invoke the Express Router
var appRoutes = require("./app/routes/api")(router); // Import the application end points/API
var path = require("path"); // Import path module
var passport = require("passport"); // Express-compatible authentication middleware for Node.js.
var social = require("./app/passport/passport")(app, passport); // Import passport.js End Points/API
app.use(morgan("dev")); // Morgan Middleware
app.use(bodyParser.json()); // Body-parser middleware
app.use(bodyParser.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(express.static(__dirname + "/public")); // Allow front end to access public folder
app.use("/api", appRoutes); // Assign name to end points (e.g., '/api/management/', '/api/users' ,etc. )
//
// <---------- REPLACE WITH YOUR MONGOOSE CONFIGURATION ---------->
//
mongoose.connect(
"mongodb://localhost:27017/databasename",
{ useNewUrlParser: true },
function(err) {
if (err) {
console.log("Not connected to the database: " + err); // Log to console if unable to connect to database
} else {
console.log("Successfully connected to MongoDB"); // Log to console if able to connect to database
}
}
);
// Set Application Static Layout
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname + "/public/app/views/index.html")); // Set index.html as layout
});
// Start Server
app.listen(port, function() {
console.log("Running the server on port " + port); // Listen on configured port
});
-
userCtrl.js
angular
.module("userControllers", ["userServices"])
// Controller: regCtrl is used for users to register an account
.controller("regCtrl", function($http, $location, $timeout, User, $scope) {
var app = this;
// Custom function that registers the user in the database
this.regUser = function(regData, valid, confirmed) {
app.disabled = true; // Disable the form when user submits to prevent multiple requests to server
app.loading = true; // Activate bootstrap loading icon
app.errorMsg = false; // Clear errorMsg each time user submits
// If form is valid and passwords match, attempt to create user
if (valid && confirmed) {
app.regData.name = app.regData.firstName + " " + app.regData.lastName; // Combine first and last name before submitting to database
// Runs custom function that registers the user in the database
User.create(app.regData).then(function(data) {
// Check if user was saved to database successfully
if (data.data.success) {
app.loading = false; // Stop bootstrap loading icon
$scope.alert = "alert alert-success"; // Set class for message
app.successMsg = data.data.message + "...Redirecting"; // If successful, grab message from JSON object and redirect to login page
// Redirect after 2000 milliseconds (2 seconds)
$timeout(function() {
$location.path("/login");
}, 2000);
} else {
app.loading = false; // Stop bootstrap loading icon
app.disabled = false; // If error occurs, remove disable lock from form
$scope.alert = "alert alert-danger"; // Set class for message
app.errorMsg = data.data.message; // If not successful, grab message from JSON object
}
});
} else {
app.disabled = false; // If error occurs, remove disable lock from form
app.loading = false; // Stop bootstrap loading icon
$scope.alert = "alert alert-danger"; // Set class for message
app.errorMsg = "Please ensure form is filled our properly"; // Display error if valid returns false
}
};
// Custom function that checks if username is available for user to use
this.checkUsername = function(regData) {
app.checkingUsername = true; // Start bootstrap loading icon
app.usernameMsg = false; // Clear usernameMsg each time user activates ngBlur
app.usernameInvalid = false; // Clear usernameInvalid each time user activates ngBlur
// Runs custom function that checks if username is available for user to use
User.checkUsername(app.regData).then(function(data) {
// Check if username is available for the user
if (data.data.success) {
app.checkingUsername = false; // Stop bootstrap loading icon
app.usernameMsg = data.data.message; // If successful, grab message from JSON object
} else {
app.checkingUsername = false; // Stop bootstrap loading icon
app.usernameInvalid = true; // User variable to let user know that the chosen username is taken already
app.usernameMsg = data.data.message; // If not successful, grab message from JSON object
}
});
};
// Custom function that checks if e-mail is available for user to use
this.checkEmail = function(regData) {
app.checkingEmail = true; // Start bootstrap loading icon
app.emailMsg = false; // Clear emailMsg each time user activates ngBlur
app.emailInvalid = false; // Clear emailInvalid each time user activates ngBlur
// Runs custom function that checks if e-mail is available for user to use
User.checkEmail(app.regData).then(function(data) {
// Check if e-mail is available for the user
if (data.data.success) {
app.checkingEmail = false; // Stop bootstrap loading icon
app.emailMsg = data.data.message; // If successful, grab message from JSON object
} else {
app.checkingEmail = false; // Stop bootstrap loading icon
app.emailInvalid = true; // User variable to let user know that the chosen e-mail is taken already
app.emailMsg = data.data.message; // If not successful, grab message from JSON object
}
});
};
app.addUser = function() {
if (app.showTheForm) {
app.showTheForm = false;
app.expand = false;
} else {
app.showTheForm = true;
app.expand = true;
}
};
})
// Custom directive to check matching passwords
.directive("match", function() {
return {
restrict: "A", // Restrict to HTML Attribute
controller: function($scope) {
$scope.confirmed = false; // Set matching password to false by default
// Custom function that checks both inputs against each other
$scope.doConfirm = function(values) {
// Run as a loop to continue check for each value each time key is pressed
values.forEach(function(ele) {
// Check if inputs match and set variable in $scope
if ($scope.confirm == ele) {
$scope.confirmed = true; // If inputs match
} else {
$scope.confirmed = false; // If inputs do not match
}
});
};
},
link: function(scope, element, attrs) {
// Grab the attribute and observe it
attrs.$observe("match", function() {
scope.matches = JSON.parse(attrs.match); // Parse to JSON
scope.doConfirm(scope.matches); // Run custom function that checks both inputs against each other
});
// Grab confirm ng-model and watch it
scope.$watch("confirm", function() {
scope.matches = JSON.parse(attrs.match); // Parse to JSON
scope.doConfirm(scope.matches); // Run custom function that checks both inputs against each other
});
}
};
});
Node.js
{ ValidationError: User validation failed: username: next is not a
function, password: next is not a function, email: next is not a function, name: next is not a function
at ValidationError.inspect (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\error\validation.js:56:24)
at ValidationError.deprecated (internal/util.js:70:15)
at formatValue (util.js:467:31)
at inspect (util.js:328:10)
at Object.formatWithOptions (util.js:182:12)
at Console.(anonymous function) (console.js:188:15)
at Console.log (console.js:199:31)
at D:\Documents\Trabajo\gorotasnewest\app\routes\api.js:70:17
at D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\model.js:4423:16
at $__save.error (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\model.js:379:16)
at D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:246:48
at next (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:167:27)
at Kareem.execPost (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:217:3)
at _handleWrapError (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:245:21)
at D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:272:14
at _next (D:\Documents\Trabajo\gorotasnewest\node_modules\kareem\index.js:94:14)
errors:
{ username:
{ ValidatorError: next is not a function
at new ValidatorError (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\error\validator.js:25:11)
at validate (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:805:13)
at D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:854:11
at Array.forEach ()
at SchemaString.SchemaType.doValidate (D:\Documents\Trabajo\gorotasnewest\node_modules\mongoose\lib\schematype.js:814:19)
I have two tabs in my admin interface. I am storing the response in my session storage. When I do the updation of any records in the tab or if I insert new record also, the same thing should be reflected in the storage also. But currently, the changes are not getting reflected in the storage. I tried my best to sort out, but I could not able to succeed. Any help/advice greatly appreciated.
Angularjs:
$scope.Pool = [];
if (!localStorageService.get('Pool')) {
Role.getPool().success(function(data) {
if (data.responseCode === 0) {
_.forEach(data.response.demoPool, function(value, key) {
dataObj = {};
dataObj.id = value.poolId;
dataObj.value = value.poolName;
$scope.Pool.push(dataObj);
});
localStorageService.set('Pool', $scope.Pool);
} else {
$scope.alerts.alert = true;
$scope.alerts.type = 'danger';
$scope.alerts.msg = data.errorMsg;
}
})
First time it will do because !localStorageService.get('Pool') becomes true. But next time it will return false because storage has value already, it will not get inside the if condition. so to resolve this remove the session storage 'Pool' to allow to execute your Role.getPool().success(function(data) {
if (!sessionStorage.length) {
// Ask other tabs for session storage
localStorage.setItem('getSessionStorage', Date.now());
};
window.addEventListener('storage', function (event) {
switch (event.key) {
case 'getSessionStorage':
// Some tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('sessionStorage');
break;
case 'sessionStorage':
// sessionStorage is empty -> fill it
var data = JSON.parse(event.newValue);
for (key in data) {
sessionStorage.setItem(key, data[key]);
}
break;
}
});
I have read the document in AngularFire 1 about Authentication. However, I cannot find out how to check whether the current user is anonymous.
Here is what I tried
.controller('IndexCtrl',['$scope','$route','Auth', function($scope,$route,Auth){
//Check whether user is existent
$scope.isExistent = function(){
var isIt = true;
if(firebaseUser.isAnonymous()){
isIt = false;
console.log("is anonyous");
}
return isIt;
};
}]);
Any help would be appreciated.
I know this is very late but the firebase user object has the property isAnonymous within it. Thus calling it as a property instead of a function should do the trick
$scope.isExistent = function(){
var isIt = true;
if(firebaseUser.isAnonymous){
isIt = false;
console.log("is anonyous");
}
return isIt;
};
I am new to Angular and I am trying to add data from forum into the database, to do so i need the id of the current user which i get with no problem, only in my post method I rely entirely on the data that i get from the forum, but in the forum i wouldn't of course ask for the id to be filled so I need to add it automatically to my controller and i don't know how to do so : here is the function that I use in my controller :
app.addFT = function () {
//Get the current user Id
Auth.getUser().then(function (data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(result)
{
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
});
});
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function (data) {
if(data.data.success){
//create success message
app.loading = false;
app.successMsg = data.data.message + '...Redirection';
//Redirect to show projet
$timeout(function () {
$location.path('/FeuillesTempsListe');
}, 2000);
}else{
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
};
app.addData is the data the user fills in the view : I get the name,description,...but I don't know how to pass the Id to app.addData other then using the forum, I tried :
app.addData.Id=lecollaborateur.Id; but it's not working , any suggestions ?
You need call createFT only after the success call of getComptebymail.
So that you will have id in the app.addData.
app.addFT = function() {
//Get the current user Id
Auth.getUser().then(function(data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(
result) {
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
app.addData.Id = lecollaborateur.Id;
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function(data) {
if (data.data.success) {
//create success message
app.loading = false;
app.successMsg = data.data.message +
'...Redirection';
//Redirect to show projet
$timeout(function() {
$location.path(
'/FeuillesTempsListe'
);
}, 2000);
} else {
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
});
});
};
I'm trying to implement Alert/Confirmation dialog boxes using the bootstrap modal service in my angular app. I want to make it generic, based on the parameter that I pass to the modal's controller it will either behave as the alert box where the user can just close it on reading the message on the modal and also it can behave like a confirmation dialog where the user should say either 'OK' or 'Cancel' I need to capture the response from the user which I'm able to. Now, the problem here is that i've list of items say in a grid and when ever user wants to delete an item from the list I need to show the confirmation message box and based on the user response I need to either delete the item or leave it if users wishes to leave it in the list, but my item is being deleted first and then the confirmation dialog is showing up, I've tried using the call back but still no use. Please help me if anyone came across this situation.
Method that shows the alert:
$scope.showAlertMessage = function (modalName,commands,callback)
{
var modalOptions = {};
var alertMessageText;
var okBtn;
var cancelBtn;
var autoCloseTimeout;
$scope.modalResp === false;
if (modalName === 'ItemNotEligible')
{
modalOptions['template'] = 'application/Views/ItemNotEligibleAlert.html';
modalOptions['cntrlr'] = 'itemAlertsController';
modalOptions['winClass'] = 'item-alert-win';
alertMessageText = commands.alertMessage.text;
okBtn=true;
cancelBtn = false;
autoCloseTimeout=commands.alertMessage.autoDismissalTimeout;
}
else if (modalName === 'ItemDelete')
{
modalOptions['template'] = 'application/Views/ItemNotEligibleAlert.html';
modalOptions['cntrlr'] = 'itemAlertsController';
modalOptions['winClass'] = 'item-alert-win';
alertMessageText = commands.alertMessage.text;
okBtn = true;
cancelBtn = true;
autoCloseTimeout = commands.alertMessage.autoDismissalTimeout;
}
var params = { alertMessage: alertMessageText};
var modalInstance=$modal.open({
templateUrl: modalOptions.template,
controller: modalOptions.cntrlr,
windowClass: modalOptions.winClass,
resolve: {
modalParams: function () {
return params;
}
}
});
modalInstance.result.then(function (selected) {
$scope.modalResp = selected; //Response from the dialog
});
callback($scope.modalResp);
}
Method where the delete item logic exists and call to show alert method is made
this.voidItem = function (skuid) {
alertMessage.text = 'Are you sure you want to remove <strong>' + itemdata[itmid].split('|')[0] + '</strong> from your list?';
$scope.showAlertMessage('ItemDelete', commands, function (userresp) {
if (userresp === true) {
var lineId = 0;
for (var i = itemListState.length - 1; i >= 0; i--) {
if (parseInt(itemListState[i].item) === itmid && Boolean(itemListState[i].isItemVoid) != true) {
lineId = itemListState[i].Id;
if (lineId != 0) {
break;
}
}
}
poService.DeleteItem(itmid, lineId, function (modal) {
virtualtable = modal;
$scope.itemCount = $scope.itemCount - 1;
$scope.createlist(itmid);
});
}
});
}
The problem is that you are executing the callback instead of chain the method to the result of the promise
modalInstance.result.then(function (selected) {
callback($scope.modalResp); //Once the promise is solved, execute your callback
$scope.modalResp = selected; //Why you need to save the response?
// If the user press cancel o close the dialog the promise will be rejected
}, onUserCancelDialogFn);
A more simple way:
modalInstance.result
.then(callback, onErrBack);