When I refresh the index page of my ember app, it appears that I can't call the functions inside my index.js file located in app/routes.
I don't really know how I can solve this issue.
The source code of index.js:
import Ember from 'ember';
import ProjectRoute from 'web/project-route';
export default ProjectRoute.extend({
authSrv: Ember.inject.service('authentication'),
_title: 'index.title',
_requireAuth: true,
beforeModel()
{
"use strict";
this._super();
},
model()
{
"use strict";
console.log(this.get('authSrv').username);
return {user_id: this.get('authSrv').user_id,
username: this.get('authSrv').username};
}
});
In the code source above we can see that I try to display the username. When I first log onto this page, it display well, but when I refresh the page, it doesn't display anything.
Any thought about it is welcomed!
So I fixed it with the Ember module RSVP. Basically, the main problem was coming from a promise. I didn't waited to catch the promise.
The index.js look like this know.
import Ember from 'ember';
import ProjectRoute from 'web/project-route';
export default ProjectRoute.extend({
authSrv: Ember.inject.service('authentication'),
_title: 'index.title',
_requireAuth: true,
beforeModel()
{
"use strict";
this._super();
},
model()
{
"use strict";
let promise = new Ember.RSVP.Promise((resolve, reject) =>
{
this.get('authSrv').get('current_auth').promise.then((res) =>
{
resolve({user_id: this.get('authSrv').user_id,
username: this.get('authSrv').username});
});
});
return promise;
}
});
Related
I'm new at ember and as first app I'm trying to build a little online shop.
I can receive "all products" as product overview but not one specific product by id.
I have following in the router.js:
Router.map(function() {
this.route('products');
this.route('product', {path: 'products/:product_id'});
});
My products.js (which works):
import Ember from 'ember';
export default Ember.Route.extend({
model(){
return this.get('store').query('product', {});
}
});
And the product.js (which does generate the problem):
import Ember from 'ember';
export default Ember.Route.extend({
model(params){
return this.store.findRecord('product', params.product_id);
}
});
The project is available under https://github.com/hatchling-shop/hatchling/tree/master/EmberHatchling
After running the code seems that you have an issue in the API in Product.findById() and not in Ember.
In the following method:
Product.findById(id, function(id, err, product) {
if (err) {
res.send(err);
}
res.json({product: product});
});
the params in the callback are wrong, instead you need to remove id and change to:
Product.findById(id, function(err, product) {
if (err) {
res.send(err);
}
res.json({product: product});
});
Hope this helps.
Folks,
I've been trying to get ESA to redirect to specific pages after login and logout events without success.
I'm trying to do this by overriding the "sessionAuthenticated" method, but have also tried setting the "routeAfterConfiguration" setting with no luck.
At the moment, login sends me to "/", and logout sends the app to "/undefined".
I'm using simple-auth-token as a JWT authenticator strategy.
The code for my application route looks like this...
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
actions: {
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
},
});
My login.js is as follows:
import Ember from 'ember';
const {service} = Ember.inject;
export default Ember.Route.extend({
session: service('session'),
errorMessage: null,
model: function(){
return Ember.Object.create({
identification:'',
password: '',
errorMessage: this.get('errorMessage')
});
},
setupController: function(controller, model) {
controller.set('credentials',model);
},
actions: {
authenticate: function(credentials) {
console.log(credentials);
this.get('session').authenticate('simple-auth-authenticator:jwt', credentials)
.catch((reason) => {
console.log('Login Error');
credentials.set('errorMessage', reason);
});
},
},
});
Does anyone have any idea what I might be doing wrong here?
Cheers,
Andy
OK. Found the problem. These are not actions - they're methods. So I just had to promote the methods out of the actions object and it's all come good.
So the correct routes/application.js looks like this:
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(ApplicationRouteMixin,{
sessionAuthenticated: function() {
console.log('sessionAuthenticated: authentications ok');
window.location.replace('/profile');
},
});
After migrating from global-namespace-version to ember-cli (0.1.4), my code doesn't work as before. I'm watching the content property in my controller to handle the data, fetched in my route. But nothing happens, the groupedResults function isn't called.
The data is fetched successfully (Ember Inspector shows all projects), so the content property shouldn't be empty.
Router
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
controllerName: 'organization-projects',
model: function() {
return this.store.find('project');
},
renderTemplate: function() {
// render all projects
this.render('organization/projects-list', {
into: 'application'
});
// render toolbar
this.render('organization/toolbar', {
into: 'application',
outlet: 'toolbar'
});
}
});
Controller
import Ember from 'ember';
export default Ember.Controller.extend({
groupedResults: function () {
console.log(this.get('content'));
}.property('content.[]')
});
Are there some breaking changes that I've missed?
Got it: changed controllerName: 'organization-projects' to controllerName: 'organization.projects'.
But I wonder why this worked in my old global-namespace-version.
I'm simply trying to write some tests to make sure logging in and out works, including everything that goes with it. Here's what I'm doing so far:
tests/integration/sessions-test.js
import Ember from "ember";
import { test } from 'ember-qunit';
import startApp from '../helpers/start-app';
var App;
module('Integrations: Sessions', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, App.destroy);
}
});
test('Unsuccessful Sign In', function() {
expect(3);
visit('/sign-in');
andThen(function() {
fillIn('input#email', 'test#user.com');
fillIn('input#password', 'bad_password');
click('input#submit');
andThen(function() {
equal(currentRouteName(), 'sign-in', 'Unsuccessfull sign in stays on the sign in page.');
ok($('input#email, input#password').hasClass('error'), 'Inputs have a class of "error."');
equal($('input#submit').prop('disabled'), false, 'Submit button is not disabled.');
});
});
});
test('Successful Sign In', function() {
expect(2);
visit('/sign-in');
andThen(function() {
fillIn('input#email', 'test#user.com');
fillIn('input#password', 'password');
click('input#submit');
andThen(function() {
equal(currentRouteName(), 'welcome', 'Successfull sign in redirects to welcome route.');
ok(find('.message').length, "Page contains a list of messages.");
});
});
});
And, here's a trimmed down version of the sign in logic behind the scenes:
app/controllers/sign-in.js
import Ember from 'ember';
export default Ember.Controller.extend({
needs: ['application'],
actions: {
signIn: function() {
var self = this;
var data = this.getProperties('email', 'password');
// Attempt to sign in and handle the response.
var promise = Ember.$.post('/v3/sessions', data);
promise.done(function(response) {
Ember.run(function() {
self.get('controllers.application').set('token', response.access_token);
self.transitionToRoute('welcome');
});
});
...
}
}
});
The "Unsuccessful Sign In" test works just fine. The "Successful Sign In" starts to work, then quits halfway through. It signs in, then redirects correctly. On the welcome page, when it makes a call to get the messages, the node server is responding with Error: Not enough or too many segments and a 500 status. What in the world does that mean and how can I fix it, assuming I don't have any control over the API?
Also, the API is written primarily using Koa and Passport, as far as I know.
Figured it out. Apparently, it was an authentication error, not that you'd ever be able to guess that by the error message.
In the sign in controller, there's a line where I was setting the token property of the application controller. The application controller had an observer to watch that property for changes, then setup the AJAX headers when it changed. Problem is, observes use Ember's run loop, which is disabled while testing.
To fix the issue, I set the AJAX headers there in the sign in controller, just before transitioning to the welcome route.
I've got the following 2 controllers:
controllers/student/index.js
import Ember from 'ember';
export default Ember.ObjectController.extend({
hasDebt: function(){
var totalCredit = this.get('totalCredit');
var totalCreditSpent = this.get('totalCreditSpent');
if (totalCreditSpent > totalCredit)
{
return true;
}
return false;
}.property('payments.#each', 'lessons.#each'),
});
controllers/students.js
import Ember from 'ember';
export default Ember.ArrayController.extend({
itemController: 'student/index',
sortProperties: ['fullName'],
sortAscending: true,
debts: function(){
var allDebts = [];
var totalDebts = 0;
this.forEach(function(student){
if (student.get('hasDebt'))
{
allDebts.push({
name: student.get('fullName'),
amount: student.get('availableCredit')
});
totalDebts += student.get('availableCredit');
}
});
return {'all': allDebts, 'total': totalDebts};
}.property('this.#each.payments', 'this.#each.lessons'),
});
And everything is working as expected. I'm able to access the hasDebt property of each element through the itemController.
Now I'd like to show the debts in a dashboard in the IndexRoute, so I've created the following additional controller, hoping to be able to access the StudentsController by using needs:
controllers/index.js
import Ember from 'ember';
export default Ember.Controller.extend({
needs: ['students'],
debts: function(){
var debts = [];
console.log( this.get('controllers.students.debts') );
this.get('controllers.students').forEach(function(student){
console.log('student');
});
return debts;
}.property(''),
});
I seem unable to access the StudentsController and any of its properties.
What am I doing wrong?
I believe that a computed property must observe a property in order to ever be populated. In your example:
controllers/index.js
export default Ember.Controller.extend({
needs: ['students'],
students: Em.computed.alias('controllers.students'),
debts: function() {
...
}.property('students.debts')
});
In this example I also made it a little easier to use Students by providing a Computed Alias mapped to students in the controller.
Debugging
It's also very handy to use the browser's console when debugging. Try running something like the following and see what comes back.
App.__container__.lookup('controller:index').get('students')
This assumes your application exists under the App namespace.