Ember Route: Cannot read property ‘id’ of undefined - javascript

I'm getting this error, where I am trying to retrieve a user that DO NOT exist on purpose ofcouse:
Error while processing route: user Cannot read property 'id' of
undefined TypeError: Cannot read property 'id' of undefined
Instead of this console error, can I give the user an error message saying, 'the user does not exist' or something like that through the route or a controller to the view?
Heres my route
App.Router.map(function () {
this.resource('user', { path: '/user/:user_id' });
});
And here i retrieve the user
App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('user', params.user_id);
},
});
Hope you understand and can help me proceed. Thanks in regards!

So I'm not sure why missing fixtures data is giving you that particular error, but you can catch errors in routes using the error event. You can read about it here. You'll have to do something like this:
App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('user', params.user_id);
},
actions: {
error: function(error, transition) {
// Display some sort of message
alert("Sorry, we couldn't find that user.");
// Redirect to a different part of the application
this.transitionTo('index');
}
}
});

Related

Acceptance test for redirect URL ember-cli

I'm trying pass an acceptance test that checks if user is redirected. When user type an URL, it should be redirected to another URL.Could someone tell me why I'm getting this error on the console?
ember.debug.js:30195 Error while processing route: account.contacts.index Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined
This is my route account/contacts/index.js
import Ember from 'ember';
export default Ember.Route.extend({
redirect: function () {
this.transitionTo('account.contacts.company');
}
});
And this is my account/contacts/index-test.js
moduleForAcceptance('Acceptance | /account/contacts/index');
test('visiting URL', function(assert) {
visit('/account/contacts');
andThen(function() {
assert.equal(currentURL(), '/account/contacts/company');
});
});
On my tests this is what I get:
Expected:"/account/contacts/company"
Result: "/account/contacts"

Catching errors in AngularJS when using $resource

Searching product is working fine when product is found, but if user search with letters, or bad criteria, nothing happens. I can see the error message in JavaScript-console and in Header there is Status Code 204, no Content. I think that Angular is just working badly, when empty object is coming back. How can I tell an user that there is no products with his/her criteria, cause I can't catch the error message at all at the moment. What is the correct and best solution to handle this? Catching errors or solving that result was empty and showing an error message in HTML-page?
Service:
return $resource(
'http://localhost:8080/RMAServer/webresources/com.rako.entity.jdeserials/:id',
{},
{
get: { method: 'GET',isArray:false, params: {id: '#serial'} },
update: { method: 'PUT', params: {id: '#serial'} }
});
Controller
//Searching product with serial number/LOTN
$scope.searchProduct = function () {
$scope.serials = lotnSvc.get({id: $scope.serial}).$promise.then(
function (data) {
var litm = data.litm;
productSvc.get({id: litm}, function (product) {
$scope.product = product;
getBrands();
},function(error){
alert('ERROR when searching product');
console.log("error---->" + error);
});
},function(error){
alert('ERROR when searching product');
console.log("error---->" + error);
});
};
Error message in javaScript console
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
http://errors.angularjs.org/1.3.15/$resource/badcfg?p0=get&p1=object&p2=array
at REGEX_STRING_REGEXP
Status code in Header
Just try to send the success and the error handlers as second and third parameters to "get" function instead of using promises. There was the same problem: How to handle $resource service errors in AngularJS

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

Object #<Object> has no method 'User'

everyone. I have a problem with my code and Meteor 0.9.4
Here is my code:
Server/publications.js
Meteor.publish('getUsers', function () {
var loggedInUser = Meteor.User();
if (Roles.userIsInRole(loggedInUser, ['admin'])) {
return Meteor.users.find({}, {fields: {
_id: 1,
emails: 1,
roles: 1
}});
}
this.stop();
return;
});
Lib/router.js
Router.map(function() {
this.route('dashboardUsers', {
layoutTemplate: 'dashboardLayout',
path: "/dashboard/users",
waitOn: function() {
return Meteor.subscribe('getUsers');
}
});
});
When I run meteor app, I have the following error:
=> App running at: http://localhost:3000/
I20141019-18:21:50.827(4)? Exception from sub 8CRiG3Jmdv4mohPhd TypeError: Object #<Object> has no method 'User'
I20141019-18:21:50.949(4)? at null._handler (app/server/publications.js:3:31)
I20141019-18:21:50.950(4)? at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
I20141019-18:21:50.950(4)? at _.extend._runHandler (packages/ddp/livedata_server.js:943)
I20141019-18:21:50.950(4)? at _.extend._startSubscription (packages/ddp/livedata_server.js:769)
I20141019-18:21:50.951(4)? at _.extend.protocol_handlers.sub (packages/ddp/livedata_server.js:582)
I20141019-18:21:50.951(4)? at packages/ddp/livedata_server.js:546
If you have a look at the docs for Meteor.user, you'll see it works everywhere except publish functions. You need to do:
var loggedInUser = Meteor.users.findOne(this.userId);
The error your getting is because of the upper-case 'u' in Meteor.User it should be Meteor.user.
However, as David Weldon pointed out you'll need to use Meteor.users.findOne(this.userId) inside of publish functions.
For anyone else running into the error Object #<Object> has no method 'user' when trying to access Meteor.user() be sure you have the accounts-base package.

Meteor.user().profile returns 'profile' undefined

I have a helper called 'isActive' and a template named 'create'.. see below
Template.create.isActive = function () {
return Meteor.user().profile.isActive;
};
When I try to run this code it returns the following in console: "Exception in template helper: TypeError: Cannot read property 'profile' of undefined".
Basically I want to pull the 'isActive' info from the current user profile and return it to the template. Any idea why this does not work?
Update
//startup on server side:
Meteor.publish("userData", function() {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'profile.isActive': 1}});
} else {
this.ready();
}
});
//startup on client side
Meteor.subscribe('userData');
//router
this.route('list', {
path: 'list',
waitOn : function () {
return Meteor.subscribe('userData');
},
data : function () {
return Meteor.users.findOne({_id: this.params._id});
},
action : function () {
if (this.ready()) {
this.render();
}
}
});
Meteor.user() is undefined. You are either not logged in with any user or your template is rendered before the users collection is synced to the client. If you use a router like iron router you can wait for the collection being available or for the user being logged on.
Without using a router the easiest would be to check if the user is defined:
Template.create.isActive = function () {
return Meteor.user() && Meteor.user().profile.isActive;
}
Since Meteor.user() is reactive the template will be rerendered when the user changes, i.e. when it is available.
This is a common error btw, see also:
Meteor.user() Error: Uncaught TypeError: Cannot read property 'name' of null
How can I prevent Meteor.user()'s timing hole?

Categories

Resources