Cannot get data passed from one function - javascript

I've a Vue component as follows:
import '../forms/form.js'
import '../forms/errors.js'
export default{
data(){
return{
form: new NewForm({
email: '',
password: '',
intendedUrl: '',
message: ''
})
}
},
methods: {
/**
* Login the user
*/
login(e) {
e.preventDefault();
this.form.startProcessing();
this.$http.post('/login/authenticate', this.form)
.then(function(response) {
this.form.finishProcessing();
},
function(response) {
this.form.setErrors(response.data);
});
}
}
}
The form.js file is
window.NewForm = function (data) {
var form = this;
$.extend(this, data);
this.errors = new NewFormErrors();
this.busy = false;
this.successful = false;
this.startProcessing = function () {
form.errors.forget();
form.busy = true;
form.successful = false;
};
this.setErrors = function (errors) {
console.log('okkk');
form.busy = false;
form.errors.set(errors);
}
};
and error.js
window.NewFormErrors = function () {
this.errors = {};
this.set = function (errors) {
console.log(errors);
this.errors= errors;
};
};
Here, the this.form.startProcessing(); seems working. But I'm not able to get the data passed to the this.setErrors. console.log(errors) returns nothing. Or it's not getting executed.

I have not recreated all of your solution but I will suspect the meaning of the value of this in the deferred execution so I will try to modify the code to:
login(e) {
e.preventDefault();
var that = this ;
this.form.startProcessing();
this.$http.post('/login/authenticate', this.form)
.then(function(response) {
that.form.finishProcessing();},
function(response) {
that.form.setErrors(response.data); });
}
I hope it will help.

Related

Object does not appear in my table. I'm trying to learn how to add an Object to the DOM with an IIFE and JSON

I don't know how to do debugging please be patient I'm a beginner and my Object does not appear on my body, I really do not know how to go on and where my problem... I think it can be that my addListItem function breaking when it tries to create a button and again when the listener is activated.
also, my details.sprites do not recognize...
my HTML is very simple and has only in the body, main and div and inside the div my ul class pokemon-list.
//IIFE
var pokemonRepository = (function () {
var pokemonList = [];
var apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150'; function loadList() {
document.write("loadList");
return fetch(apiUrl).then(function (response) {
return response.json();
document.write("loadList fetch \n");
}).then(function (json) {
document.write("loadList then \n");
json.results.forEach(function (item) { //result /results
var pokemon = {
name: item.name,
detailsUrl: item.url
};
add(pokemon);
})
}).catch(function (e) {
document.write("loadDetails catch error\n");
console.error(e);
})
}
function loadDetails(item) {
document.write("loadDetails \n");
var url = item.detailsUrl;
return fetch(url).then(function (response) {
return response.json();
document.write("loadDetails then\n");
}).then(function (details) {
//item.imageUrl = details.sprites.front_default; //do not know sprities ???
item.height = details.height;
item.types = details.types;
}).catch(function (e) {
console.error(e);
});
}
function showDetails(item) {
loadDetails(item).then(function () {
})
}
return{
add: add,
getAll: getAll,
loadList: loadList,
loadDetails: loadDetails,
showDetails: showDetails
};
})();
function addListItem(pokemone) {
var container = document.querySelector('.pokemon-list');
var listItem = document.createElement('li');
var button = document.createElement('button');
button.innerText = pokemone.name;
container.appendChild(listItem); //object breaks
listItem.appendChild(button);
button.addEventListener('click', function (event) { //object breaks
pokemonRepository.showDetails(pokemone);
});
}
pokemonRepository.loadList().then(function () {
pokemonRepository.getAll().forEach(function (pokemon) {
addListItem(pokemon);
})
})

Axios 'Get' Function Not Calling

So, I am wanting to retrieve an updated list of contacts on once a new contact is added. Unfortunately, axios is only loading the get request on the 'beforeMount()' instance. When I try and call the function inside of an axios.post request when it's successful, the list of contacts is gone until I refresh the page again.
I'm running Laravel 5.7 and VueJs 2.5.22.
import axios from 'axios';
export default {
data() {
return {
companion: {
name: '',
desc: '',
primaryPhone: '',
secondaryPhone: '',
email: '',
address: '',
notes: '',
image: ''
},
characterAmount: 0
};
},
props: {
addCompanion: {
type: Boolean
}
},
methods: {
checkNotesLength(e) {
this.characterAmount =
document.getElementById('notes').value.length;
if (e.keyCode === 8) {
this.characterAmount--;
if (this.characterAmount < 0) {
this.characterAmount = 0;
}
} else {
this.characterAmount++;
if (this.characterAmount > 150) {
this.characterAmount = 150;
}
}
},
processFile(e) {
var input = e.target;
var reader = new FileReader();
reader.onload = (e) => {
this.companion.image = e.target.result;
}
reader.readAsDataURL(input.files[0]);
},
getCompanions() {
const url = window.location + 'companions';
axios.get(url)
.then((response) => {
this.companions = response.data;
})
.catch((error) => {
// handle error
console.log(error);
});
},
submitCompanion() {
const formData = {
name: this.companion.name,
desc: this.companion.desc,
primaryPhone: this.companion.primaryPhone,
secondaryPhone: this.companion.secondaryPhone,
email: this.companion.email,
address: this.companion.address,
notes: this.companion.notes,
image: this.companion.image
}
axios.post('/companion/create', formData)
.then(this.getCompanions())
.then((response) => {
this.addCompanion = !this.addCompanion;
//need to clear form and include messages, also need to add validation
})
.catch((error) => {
console.log(error);
});
}
}
}
The beforeMount() function is on my App.vue, which just calls the same getCompanions function as the above one you see.
The issue that I see in your code is that you are not passing the callback correctly. This code will execute the function getCompanions() immediately:
.then(this.getCompanions())
To pass it as a callback try something like this
.then(this.getCompanions.bind(this))
// OR
.then(() => this.getCompanions())
This is probably because your url structure is wrong.
const url = window.location + 'companions';
should be
const url = window.location + '/companions';

Function is not recognized by another function in angularjs

During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}

firebase invalid email authentication error

When I login to my firebase v 2.4.1 app using email / password auth with an invalid email. Firebase throws an error internally and I can't seem to find a way to catch it.
The examples here work, but they are using v.1.1.1 and when I swap the libraries in my app to 1.1.1 it seems to work also
Am I missing something or is this a known issue?
http://jsfiddle.net/firebase/a221m6pb/embedded/result,js/
(function (jQuery, Firebase, Path) {
"use strict";
// the main firebase reference
var rootRef = new Firebase('https://docs-sandbox.firebaseio.com/web/uauth');
// pair our routes to our form elements and controller
var routeMap = {
'#/': {
form: 'frmLogin',
controller: 'login'
},
'#/logout': {
form: 'frmLogout',
controller: 'logout'
},
'#/register': {
form: 'frmRegister',
controller: 'register'
},
'#/profile': {
form: 'frmProfile',
controller: 'profile',
authRequired: true // must be logged in to get here
},
};
// create the object to store our controllers
var controllers = {};
// store the active form shown on the page
var activeForm = null;
var alertBox = $('#alert');
function routeTo(route) {
window.location.href = '#/' + route;
}
// Handle third party login providers
// returns a promise
function thirdPartyLogin(provider) {
var deferred = $.Deferred();
rootRef.authWithOAuthPopup(provider, function (err, user) {
if (err) {
deferred.reject(err);
}
if (user) {
deferred.resolve(user);
}
});
return deferred.promise();
};
// Handle Email/Password login
// returns a promise
function authWithPassword(userObj) {
var deferred = $.Deferred();
console.log(userObj);
rootRef.authWithPassword(userObj, function onAuth(err, user) {
if (err) {
deferred.reject(err);
}
if (user) {
deferred.resolve(user);
}
});
return deferred.promise();
}
// create a user but not login
// returns a promsie
function createUser(userObj) {
var deferred = $.Deferred();
rootRef.createUser(userObj, function (err) {
if (!err) {
deferred.resolve();
} else {
deferred.reject(err);
}
});
return deferred.promise();
}
// Create a user and then login in
// returns a promise
function createUserAndLogin(userObj) {
return createUser(userObj)
.then(function () {
return authWithPassword(userObj);
});
}
// authenticate anonymously
// returns a promise
function authAnonymously() {
var deferred = $.Deferred();
rootRef.authAnonymously(function (err, authData) {
if (authData) {
deferred.resolve(authData);
}
if (err) {
deferred.reject(err);
}
});
return deferred.promise();
}
// route to the specified route if sucessful
// if there is an error, show the alert
function handleAuthResponse(promise, route) {
$.when(promise)
.then(function (authData) {
// route
routeTo(route);
}, function (err) {
console.log(err);
// pop up error
showAlert({
title: err.code,
detail: err.message,
className: 'alert-danger'
});
});
}
// options for showing the alert box
function showAlert(opts) {
var title = opts.title;
var detail = opts.detail;
var className = 'alert ' + opts.className;
alertBox.removeClass().addClass(className);
alertBox.children('#alert-title').text(title);
alertBox.children('#alert-detail').text(detail);
}
/// Controllers
////////////////////////////////////////
controllers.login = function (form) {
// Form submission for logging in
form.on('submit', function (e) {
var userAndPass = $(this).serializeObject();
var loginPromise = authWithPassword(userAndPass);
e.preventDefault();
handleAuthResponse(loginPromise, 'profile');
});
// Social buttons
form.children('.bt-social').on('click', function (e) {
var $currentButton = $(this);
var provider = $currentButton.data('provider');
var socialLoginPromise;
e.preventDefault();
socialLoginPromise = thirdPartyLogin(provider);
handleAuthResponse(socialLoginPromise, 'profile');
});
form.children('#btAnon').on('click', function (e) {
e.preventDefault();
handleAuthResponse(authAnonymously(), 'profilex');
});
};
// logout immediately when the controller is invoked
controllers.logout = function (form) {
rootRef.unauth();
};
controllers.register = function (form) {
// Form submission for registering
form.on('submit', function (e) {
var userAndPass = $(this).serializeObject();
var loginPromise = createUserAndLogin(userAndPass);
e.preventDefault();
handleAuthResponse(loginPromise, 'profile');
});
};
controllers.profile = function (form) {
// Check the current user
var user = rootRef.getAuth();
var userRef;
// If no current user send to register page
if (!user) {
routeTo('register');
return;
}
// Load user info
userRef = rootRef.child('users').child(user.uid);
userRef.once('value', function (snap) {
var user = snap.val();
if (!user) {
return;
}
// set the fields
form.find('#txtName').val(user.name);
form.find('#ddlDino').val(user.favoriteDinosaur);
});
// Save user's info to Firebase
form.on('submit', function (e) {
e.preventDefault();
var userInfo = $(this).serializeObject();
userRef.set(userInfo, function onComplete() {
// show the message if write is successful
showAlert({
title: 'Successfully saved!',
detail: 'You are still logged in',
className: 'alert-success'
});
});
});
};
/// Routing
////////////////////////////////////////
// Handle transitions between routes
function transitionRoute(path) {
// grab the config object to get the form element and controller
var formRoute = routeMap[path];
var currentUser = rootRef.getAuth();
// if authentication is required and there is no
// current user then go to the register page and
// stop executing
if (formRoute.authRequired && !currentUser) {
routeTo('register');
return;
}
// wrap the upcoming form in jQuery
var upcomingForm = $('#' + formRoute.form);
// if there is no active form then make the current one active
if (!activeForm) {
activeForm = upcomingForm;
}
// hide old form and show new form
activeForm.hide();
upcomingForm.show().hide().fadeIn(750);
// remove any listeners on the soon to be switched form
activeForm.off();
// set the new form as the active form
activeForm = upcomingForm;
// invoke the controller
controllers[formRoute.controller](activeForm);
}
// Set up the transitioning of the route
function prepRoute() {
transitionRoute(this.path);
}
/// Routes
/// #/ - Login
// #/logout - Logut
// #/register - Register
// #/profile - Profile
Path.map("#/").to(prepRoute);
Path.map("#/logout").to(prepRoute);
Path.map("#/register").to(prepRoute);
Path.map("#/profile").to(prepRoute);
Path.root("#/");
/// Initialize
////////////////////////////////////////
$(function () {
// Start the router
Path.listen();
// whenever authentication happens send a popup
rootRef.onAuth(function globalOnAuth(authData) {
if (authData) {
showAlert({
title: 'Logged in!',
detail: 'Using ' + authData.provider,
className: 'alert-success'
});
} else {
showAlert({
title: 'You are not logged in',
detail: '',
className: 'alert-info'
});
}
});
});
}(window.jQuery, window.Firebase, window.Path))
I removed the 1.1.1 reference from your jsFiddle and added the 2.4.1 one (https://cdn.firebase.com/js/client/2.4.1/firebase.js) and then tried it with a random email and it reacted exactly the same as with the previous version. Can you give me more details on how to reproduce it? I was using Chrome.

Property in service not updated

Having a little trouble with my authentication service. I basically have this on my service:
angular.factory('authentication', [..., function() {
var currentUser = {};
return {
login: function() {
currentUser = { username: 'Foo' };
},
logout: function() {
currentUser = {};
}
user: currentUser;
}
})]
And in my AppCtrl, I have this:
angular.module('App').controller('AppCtrl', [..., function() {
$rootScope.$on('$stateChangeSuccess', function() {
console.log(authentication.user);
});
}]);
In my LogoutCtrl, I have this:
angular.controller('LogoutCtrl', [..., function() {
authentication.logout();
$state.go('login');
}]);
Once the state changes to login, the console still prints username: 'Foo'.
Any ideas?
When you make the first assignment in the object you are referring to the reference of the user. You then replace that reference when you call logout() so your old user, bound earlier, is unchanged. Change it to a getter function instead:
...
getUser: function() {
return user; // always the correct reference
}
Now call that in the console.log and it will work
angular.factory('authentication', [..., function() {
var currentUser = {};
return {
login: function() {
currentUser = { username: 'Foo' };
},
logout: function() {
currentUser = {};
}
user: currentUser;
}
})]
Your login/logout methods change the value of the variable currentUser. These changes are not propagated to the authentication.property.
Two possible fixes:
1) Use this.user instead of var currentUser:
angular.factory('authentication', [..., function() {
return {
login: function() {
this.user = { username: 'Foo' };
},
logout: function() {
this.user = {};
}
user: {};
}
})]
2) Implement user as a getter-based property:
angular.factory('authentication', [..., function() {
var currentUser = {};
var auth = {
login: function() {
currentUser = { username: 'Foo' };
},
logout: function() {
currentUser = {};
}
};
Object.defineProperty(auth, 'user', {
get: function() { return currentUser; }
});
return svc;
})]

Categories