Ember.js - How to properly call the store from a controller? - javascript

so I am trying to access the store from a controller like so:
import Ember from 'ember';
export default Ember.Controller.extend({
emailAddress: '',
message: '',
isValidEmail: Ember.computed.match('emailAddress', /^.+#.+\..+$/),
isMessageLongEnough: Ember.computed.gte('message.length', 10),
isValid: Ember.computed.and('isValidEmail', 'isMessageLongEnough'),
isNotValid: Ember.computed.not('isValid'),
actions: {
sendConfirmation() {
this.store.createRecord('contact', {
email: emailAddress,
message: message,
}).save();
this.set('responseMessage', 'We got your message and we will be in contact soon :)');
this.set('emailAddress', '');
this.set('message', '');
}
}
});
I looked at the documentation for Ember.js 2.7 and it doesn't specifically tell you where one can have access to the store, but I know it can be access it through a controller or route.
However, doing it this way gives me these errors:
controllers/contact.js: line 17, col 16, 'emailAddress' is not defined.
controllers/contact.js: line 18, col 18, 'message' is not defined.
I'm not sure if it's the way I am accessing the controller, or the way I defined emailAddress and message.
Please help and thank you!
SOLVED:
For this part:
sendConfirmation() {
this.store.createRecord('contact', {
email: emailAddress,
message: message,
}).save();
It should have been this:
sendConfirmation() {
this.store.createRecord('contact', {
email: this.get('emailAddress'),
message: this.get('message'),
}).save();
:)

Your problem is not the way you access the store, it's that you're trying to add a contact with an email and a message without actually defining the variables.
sendConfirmation() {
this.store.createRecord('contact', {
// what do you expect emailAddress and message values to be at this point?
email: emailAddress, // <-- emailAddress is not defined
message: message, // <-- message is not defined
}).save();
// ...
Did you perhaps mean to retrieve them first?
sendConfirmation() {
// retrieve emailAddress and message first
const {
emailAddress,
message
} = this.getProperties('emailAddress', 'message');
// then use them to create a contact
this.store.createRecord('contact', {
email: emailAddress
message: message
}).save();
// ...
One more thing, accessing the store should probably be done using this.get('store'), since using getters/setters is the ember-way of accessing/manipulating properties.

By default store will be injected into controller and route. and one more thing you should get properties through get
sendConfirmation() {
var newRecordObj = {};
newRecordObj['email'] = this.get('emailAddress');
newRecordObj['message'] = this.get('message');
this.get('store').createRecord('contact', newRecordObj).save((result) => {
//success handling
this.set('responseMessage', 'We got your message and we will be in contact soon :)');
this.set('emailAddress', '');
this.set('message', '');
}, () => {
//error handling
this.set('responseMessage', 'Error message');
});
}

Related

NodeJS - Updating object on request

I have the following object:
var user = {
firstName: req.body.first_name,
lastName: req.body.last_name,
email: req.body.email,
password: "",
id: "",
};
Now what I'm trying to do is post a request to the API and if the user is successfully saved in the database, it will return a user id as well as a password (Which can then be emailed to the person)..
request.post({
url: process.env.API_SIGNEDIN_ENDPOINT + "users/store",
form: user,
headers: {
Authorization: "Bearer " + req.session.authorization
}
}, function(error, response, body) {
// Check the response
var theResponse = JSON.parse(response.body);
if(theResponse.code == 400)
{
var error = [
{param: "email", msg: "This email address has already been taken!", value: ""}
];
res.render("create", {
errors: error,
});
}else{
var theUser = JSON.parse(body);
user.password = theUser.password;
user.id = theUser.id;
}
});
This is working fine, however, whenever I try to output user it's not updating the user object outside of this post. The user object is fine and it's working, the issue seems to be from when I try and access the user from this result callback. Any ideas?
EDIT:
Let's say I have "address1" (This is the persons main address) and I have "address2" (This is the persons second address).. The person might only have 1 address and therefore I only need to save one address. However using the logic that place everything in the .then() means I cannot do this because the user might not have 2 addresses but I still need to access the main address, for example:
mainAddress.save().then(function(addressData) {
var theAddressLicenceTick = req.body.address_licence;
if(theAddressLicenceTick)
{
var subAddress = models.addresses.build({
address_1: "asasfasf",
city: "asfafsaf",
postcode: "asfasf",
created_at: new Date(),
updated_at: new Date();
});
subAddress.save().then(function(subAddress) {
// continue integration
// would I have to do the functionality again?
});
}else{
// The user only has one address
}
});
Essentially, I have a customer table which can have multiple addresses through a link table. But I believe that there is an easier way instead of writing all of this code?

Meteor.JS - accounts-password : TypeError: Accounts.createUser is not a function

I am creating one app and getting the following error:
TypeError: Accounts.createUser is not a function
Here is my Code:
Template.register.events({
'submit form': function(event){
event.preventDefault();
var email = $('[name=email]').val();
var password = $('[name=password]').val();
var fname = $('[name=fname]').val();
var lname = $('[name=lname]').val();
Accounts.createUser({
email: email,
password: password,
profile: {
fname: fname,
lname: lname,
IsActive: 0
}
});
Router.go('home');
}
});
I am using the : accounts-password package
I am also using the MONGO_URL (MONGO_URL=mongodb://localhost:27017/MYDB)
I have tried : meteor reset
also recreated the app by : meteor create myapp
I can login thru the already created user, Previously it was not giving any issues and I created one User, but now it is giving this issue, What should I do?
Here is what I was doing wrong :
I was using a collection having a name as Accounts, see below :
OLD CODE
Accounts = new Meteor.Collection('accounts');
Subscriptions :
Meteor.publish('Accounts', function(){
return Accounts.find();
});
and using the Helpers:
Template.account_screen_account_view.helpers({
FetchAccountViewData: function () {
var editid = Router.current().params._id;
return CustomerAccounts.findOne({_id:editid});
}
});
It was conflicting with the following code:
Accounts.createUser({
email: email,
password: password,
profile: {
fname: fname,
lname: lname,
IsActive: 0
}
});
NEW CODE (CHANGED)
CustomerAccounts = new Meteor.Collection('customeraccounts');
Meteor.publish('CustomerAccounts', function(){
return CustomerAccounts.find();
});
Template.account_screen_account_view.helpers({
FetchAccountViewData: function () {
var editid = Router.current().params._id;
return CustomerAccounts.findOne({_id:editid});
}
});
Now the issue is resolved. Sometimes we forget to look into these things, I am happy to share my experience as if you use Meteor Accounts, then you need to change the name of your own collections and functions as they can conflict and create these type of issues.
Please verify your field names same or not.
If those are same try this:
funname:function(event,target){
email=target.find(".your field class name or # field id").value;
}

Username not changing properly using MongoDB update function?

Below is a snippet of my code where I begin by searching the collection of notes to see if any of them contain the username that I am changing my current session's username to. If the username has not yet been used, it may be changed to that so I change the current session's username and then I update every note to be under this new username then display a changesuccess.jade file. However, when I run the code everything appears to run fine exept the username for each note doesn't change. I feel like it's due to the find() method on the 5th line. Any help would be greatly appreciated!
router.post('/changeusername',function(req, res) {
var newUsername = req.body.username;
var user = req.session.username;
var userFound = notesCollection.find( { owner: newUsername } )
var results = function(infoInput) {
res.render("changedUser.jade", {title: "Username Change",
info: infoInput});
}
var checkChange = function(err) {
if (err) {
results("Username change failed!");
} else {
results("Username changed!");
}
}
console.log(userFound);
if (!userFound.length) {
notesCollection.update({ owner: user },
{ owner: newUsername},
{ multi: true },
checkChange);
} else {
res.render("changedUser.jade", {title: "Username Change",
info: "Username change failed!"});
}
});
If i understand your problem correctly, you are trying to update a collection in mongodb and it is not getting updated.
So the problem is with the way you are calling mongoose#update.
Since you want to update 'owner', you should use mongodb#$set
Mongoose supports the same $set operator in the conditions too.
So just a little correction for your case:
var conditions = { owner: user }
, update = { $set: { owner: newUsername }}
, options = { multi: true };
notesCollection.update(conditions, update, options, callback);
function callback (err, numAffected) {
// numAffected is the number of updated documents
})
So try this now.

angularjs message binding doesn't show until second form submit [duplicate]

This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 8 years ago.
I'm writing my first angularjs app, and it's beginning to make sense. However, I have a sign up form that isn't getting the messages in some cases to alert users to problems. I'm using Firebase to authenticate, which works fine. But I'm storing users by a unique username as the key. So before I run the $createUser function, I do a quick query to see if there's already a user object with this key-- if not, I create the user.
The problem is when there is an existing user with this username. The console log value prints fine, but the error message (bound to $scope.authMsg) doesn't show up the first time-- but if I click the "register" button again, then the message shows up in the expected message div.
Any hints on the message issue (or suggestions for this code) would be appreciated!
$scope.register = function() {
$scope.authMsg = '';
var ref = new Firebase(FIREBASE_URL);
$scope.authObj = $firebaseAuth(ref);
// check if the username is taken
ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
if (snapshot.val()) {
//
// PROBLEM HERE!!
//
$scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
console.log('Username exists-- did you forget your password?'); // prints to console as expected
} else {
$scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
.then(function(userData) {
console.dir(userData);
return $scope.authObj.$authWithPassword({
email: $scope.account.email,
password: $scope.account.password
});
}).then(function(authData) {
// we created a user and are now logged in-- store user info
var userdata = {};
userdata[$scope.account.username] = {
uid: authData.uid,
first_name: $scope.account.first_name,
last_name: $scope.account.last_name,
email: $scope.account.email,
full_name: $scope.account.first_name+' '+$scope.account.last_name
};
var usersRef = ref.child("users");
// save the userdata
usersRef.set(userdata);
console.log("Logged in as:", authData.uid);
$state.go('app.dashboard');
}).catch(function(error) {
$scope.authMsg = error;
console.error("Error: ", error);
});
}
}, function (errorObject) {
$scope.authMsg = 'The read failed: ' + errorObject.code;
console.log('The read failed: ' + errorObject.code);
});
};
I'm assuming, the Firebase callback does not involve an angular digest cycle.
To handle this, write
if (snapshot.val()) {
$scope.$apply(function() {
$scope.authMsg = 'Username exists— did you forget your password?';
});
A useful reading about the topic: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Ember data: Rollback createRecord on error

I'm trying to find the best way to avoid adding a record when there's an error using Ember Data:
This is my code:
createUser: function() {
// Create the new User model
var user = this.store.createRecord('user', {
firstName: this.get('firstName'),
lastName: this.get('lastName'),
email: this.get('email')
});
user.save().then(function() {
console.log("User saved.");
}, function(response) {
console.log("Error.");
});
},
I'm validating the schema on backend and returning a 422 Error in case it fails.
If I don't handle the error, the record is added to the site and I also get a console error.
So I did this:
user.save().then(function() {
console.log("User saved.");
}, function(response) {
user.destroyRecord();
});
Which kind of works deleting the record after reading the server response but:
1) I see the record appearing and dissapearing (like a visual glitch to say it somehow).
2) The console error still appears.
Is there a way to better handle this? I mean, is there a way to avoid adding the record when the server returns an error? Is there a way to avoid showing the console error?
Thanks in advance
You'll need to catch the error in the controller and then use deleteRecord() to remove it from the store:
actions: {
createContent() {
let record = this.store.createRecord('post', {
title: ''
});
record.save()
.then(rec => {
// do stuff on success
})
.catch(err => {
record.deleteRecord();
// do other stuff on error
});
}
}

Categories

Resources