Getting data from function - javascript

I am having some trouble getting the logged in status from the below function.
I can set the loggedIn status with currentUser.setProfile(username, token), which works.
But when i then try to get the isLoggedIn afterwards, i can't seem to get it.
console.log(currentUser) return the 2 functions, setProfile and getProfile. But getProfile is just an empty function.
I have tried currentUser.getProfile.isLoggedIn among others, but they all just return undefined.
What am i doing wrong?
Function:
(function () {
"use strict";
angular
.module("myApp")
.factory("currentUser",
currentUser)
function currentUser() {
var profile = {
isLoggedIn: false,
username: "",
token: ""
};
var setProfile = function (username, token) {
profile.username = username;
profile.token = token;
profile.isLoggedIn = true;
};
var getProfile = function () {
return profile;
}
return {
setProfile: setProfile,
getProfile: getProfile
}
}
})();

Because getProfile is a function, you should call it like
currentUser.getProfile().isLoggedIn

Related

Mailchimp API returning 'undefined'

I am trying to implement an API to read if user exists as a member in my mailchimp account and if it is not there then add this member to the list.
I am using #marketing/mailchimp_marketing library as a reference (https://github.com/mailchimp/mailchimp-marketing-node).
The issue: mailchimp is returning 'undefined'. Maybe I am missing something in the code and I am afraid setConfig is not been read (not sure). I really appreciate your support. This is the code used:
const md5 = require('md5');
const mailchimp = require('#mailchimp/mailchimp_marketing');
mailchimp.setConfig({
apiKey: 'my-api-key',
server: 'my-server',
});
const listId = '#listcode';
async function checkstatus(subscriber) { //subscriber is an object received from another js file through
//checkstatus function.
console.log(subscriber); // returns the object ok
const status_id = 'subscribed';
for (let i = 0; i < subscriber.length - 24; i++) {
const no_email = subscriber[i].email.toLowerCase();
const subscriberHash = md5(no_email);
const FNAME_Name = subscriber[i].nome;
const LNAME_Name = subscriber[i].sobrenome;
try {
const response = await mailchimp.lists.getListMember(
listId,
subscriberHash
);
console.log(`${response.status}`); // returns 'undefined'
} catch (e) {
console.error(e.status); // returns 'undefined'
console.log('nao cadastrado');
addmember(no_email, FNAME_Name, LNAME_Name, status_id);
}
}
alert('Done');
}
export { checkstatus };
async function addmember(no_email, FNAME_Name, LNAME_Name, status_id) {
try {
const run = async () => {
const additional = await mailchimp.lists.addListMember(listId, {
email_address: no_email,
status: status_id,
merge_fields: {
FNAME: FNAME_Name,
LNAME: LNAME_Name,
},
});
console.log(
`Successfully added contact as an audience member. The contact's id is ${additional.id}.`
);
};
run();
} catch (e) {
//console.error(e.status);
console.log(e.status);
}
return;
}

Global method this.$t from vue-i18n does not work in function

I define vue-I18n globally:
Vue.use(VueI18n);
export default new VueI18n({
locale: process.env.VUE_APP_I18N_LOCALE || 'cs',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'cs',
messages: loadLocaleMessages(),
});
I can use it anywhere with:
this.$t('sign-up.something-went-wrong')
But not inside a for each loop, probably because new anonymous class is created. How can I reference it from there?
function convertErrors(jsonErrors) {
const veeErrors = {};
console.log(this.$t('sign-up.heading'));
return veeErrors;
}
And called from export.default
methods: {
async submitForm() {
try {
const { data } = await this.$store.dispatch('CREATE_USER_PROFILE', {
email: this.email,
password: this.password,
nickname: this.nickname,
});
if (!this.personalData) {
this.success = true;
return true;
}
if (data.token === undefined) {
this.error = this.$t('sign-up.something-went-wrong');
return false;
}
const jwtData = jwtDecode(data.token);
const vehicles = [];
setVehicles.call(this, vehicles);
await this.$store.dispatch('UPDATE_USER_PROFILE', {
jwt: data,
userId: jwtData.userId,
});
this.success = true;
} catch (error) {
this.success = false;
if (error.response) {
console.log(this.$t('sign-up.something-went-wrong')); // this works
const veeErrors = convertErrors(error.response.data); // this fails
this.$refs.form.setErrors(veeErrors);
} else {
this.error = this.$t('sign-up.something-went-wrong');
}
}
return this.success;
},
},
I can see the following error in the chrome console:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property '$t' of undefined"
And
TypeError: Cannot read property '$t' of undefined
at convertErrors (SignUpForm.vue?9fa9:236)
at VueComponent._callee$ (SignUpForm.vue?9fa9:321)
at tryCatch (runtime.js?96cf:45)
convertErrors has no "this", it's not bound to a component. Move it into the component's methods in order to reference this:
methods: {
convertErrors(jsonErrors) {
const veeErrors = {};
console.log(this.$t('sign-up.heading'));
return veeErrors;
}
}
OR
use call in order to set the context (the this) inside convertErrors:
const veeErrors = convertErrors.call(this, error.response.data);
You can store VueComponent before for each loop. Like this one:
let self = this
// .......
jsonErrors.errors.forEach((error) => {
if (error.field) {
veeErrors.$field = [self.$t(error.messageKey)];
} else {
self.error = self.$t(error.messageKey);
}
});

Keep Session Angularjs Authentication

I'm using the Jason project that you can find at this link in my project.
I'm using AngularJS 1.6.4 with WildFly 10 with Java 8 and SQL Server 2014. I can get the login correction, but when I refresh the page the same does not hold the session.
What could be happening? Besides the adaptations I have to do in 'user.service.js', do I have to change anything else to be able to keep the session?
My code user.service.js
(function () {
'use strict';
angular
.module('app')
.factory('UserService', UserService);
UserService.$inject = ['$http'];
function UserService($http) {
var service = {};
//service.GetAll = GetAll;
//service.GetById = GetById;
service.GetByUsername = GetByUsername;
service.Create = Create;
//service.Update = Update;
//service.Delete = Delete;
return service;
//function GetAll() {
// return $http.get('rest/usuarios/login/').then(handleSuccess, handleError('Error getting all users'));
//}
//function GetById(id) {
// return $http.get('rest/usuarios/login/' + id).then(handleSuccess, handleError('Error getting user by id'));
//}
function GetByUsername(usermatricula, usersenha) {
return $http.post('rest/usuarios/login/' + usermatricula + '/' + usersenha).then(handleSuccess, handleError('Error getting user by username'));
}
function Create(user) {
return $http.post('rest/usuarios/', user).then(handleSuccess, handleError('Error creating user'));
}
//function Update(user) {
// return $http.put('rest/usuarios/login/' + user.id, user).then(handleSuccess, handleError('Error updating user'));
//}
//function Delete(id) {
// return $http.delete('rest/usuarios/login/' + id).then(handleSuccess, handleError('Error deleting user'));
//}
// private functions
function handleSuccess(res) {
console.log(res.data);
return res.data;
}
function handleError(error) {
return function () {
return { success: false, message: error };
};
}
}
})();
You can store user data in localStorage when you get response from request as below
function handleSuccess(res) {
console.log(res.data);
// Put the object into storage
localStorage.setItem('userSession', JSON.stringify(res.data));
return res.data;
}
To check if a session exists you can do
// If an object named userSession exists in the local storage
if(localStorage.getItem('userSession')){
// Retrieve the object from storage
var userSession = JSON.parse(localStorage.getItem('userSession'));
}
And then check data in userSession

Asynchronous function inside asynchronous function

I have this block of code in a function:
this.apiService.fetchCategories(!this.cacheData).subscribe(
response => {
if(this._jsnValService.valCategories(response)) {
this.customerMap.categories = this.formatCategories(response["categories"]);
} else {
alert("Categories failed the schema validation. Please contact support if this happens again.");
}
},
error => {
this.notification.title = "Oops, there's a problem.";
this.notification.content = "Seems there's an issue getting the provider categories.";
this.notification.show("provider_categories_api");
}
);
It fetches some data and then runs a validation on the data (if(this._jsnValService.valCategories(response)) {).
However, my validation of the data is actually async too, because it validates it against a json schema which is in a seperate json file so it has to read the file first.
I have used a promise to read the file contents and then do the validation:
#Injectable()
export class ValidateJSONSchemaService {
constructor(private http: Http) {}
public valCategories(json) {
this._getSchema("./jsonSchema.categories.json").then((schema) => {
this._valSchema(json, schema);
});
};
private _valSchema(json, schema): any {
var ajv = new Ajv();
var valid = ajv.validate(schema, json);
if (!valid) {
console.log(ajv.errors);
return false;
} else {
console.log(valid);
return true;
};
};
private _getSchema(fileName): any {
return new Promise((resolve, reject) => {
this.http.get(fileName)
.map(this._extractData)
.catch(this._handleError)
.subscribe(schema => resolve(schema));
});
};
private _extractData(res: Response) {
let body = res.json();
return body.data || {};
};
How can I edit the top code block in this question to account for the asynchronous function inside the if statement (if(this._jsnValService.valCategories(response)) {)?
if you are using ES6 you could use async/await like this:
async function _validateCategories() {
this.apiService.fetchCategories(!this.cacheData).subscribe(
response => {
const valid = await this._jsnValService.valCategories(response)
if(valid) {
this.customerMap.categories = this.formatCategories(response["categories"]);
} else {
alert("Categories failed the schema validation. Please contact support if this happens again.");
}
},
error => {
this.notification.title = "Oops, there's a problem.";
this.notification.content = "Seems there's an issue getting the provider categories.";
this.notification.show("provider_categories_api");
}
);
}
if not, your function fetchCategories should return a promise or allow you to pass a callback to do something like this:
async function _validateCategories() {
this.apiService.fetchCategories(!this.cacheData).subscribe(
response => {
this._jsnValService.valCategories(response).then((error, valid)=> {
if(error) {
alert("Categories failed the schema validation. Please contact support if this happens again.");
}
this.customerMap.categories = this.formatCategories(response["categories"]);
})
},
error => {
this.notification.title = "Oops, there's a problem.";
this.notification.content = "Seems there's an issue getting the provider categories.";
this.notification.show("provider_categories_api");
}
);
}

Javascript object method does not update variable

var myUser = (function () {
var username = "",
var isConnected = false;
return {
setUsername: function (n) {
username = n;
},
setConn: function (connStatus) {
isConnected = connStatus;
},
user: username,
isCon: isConnected
};
}());
When I call
myUser.setUsername("user123");
username variable does not get updated.
Any advice?
It looks like you want to use myUser.user to refer the updated username value.
However, if that's the case, it doesn't work. setUsername updates username variable, but myUser.user only points to username's initial value, which is "". It won't points to the updated username value
to fix the problem, you can change
user: username,
to
user: function() {
return username;
},
This might be a better case to use prototype model:
function User(prop) {
prop = prop || {};
this.username = prop.username || '';
this.isConnected = prop.isConnected || false;
}
User.prototype = {
setUser: function(uname) { this.username = uname; },
setConn: function(status) { this.isConnected = status; }
};
var myUser = new User();
myUser.setUser('user1234');
// OR
var myUser = new User({ username: 'user1234' });
console.log(myUser.username); //=> 'user1234'
....
},
user: username,
isCon: isConnected
user: username forces the username to be evaluated, which returns "". This is more easy to figure out what happend
var obj = {
log: console.log("printed when init")
}

Categories

Resources