Reputation: 23443
I am trying set a value into userSessionStorage
, when i am accessing it from the authenticate() function it seems to work correctly.
However, it is not working in the .then() promise.
app/controllers/show.js
import Ember from 'ember';
import { storageFor } from 'ember-local-storage';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
userSessionStorage: storageFor('user'),
authenticator: 'authenticator:custom',
actions: {
authenticate: function() {
var credentials = this.getProperties('identification', 'password');
// ok
this.set('userSessionStorage.username', credentials.identification);
this.get('session').authenticate('authenticator:custom', credentials)
.then(function(){
// error: TypeError: Cannot read property 'set' of undefined
this.set('userSessionStorage.username', credentials.identification);
})
.catch((message) => {
console.log("message: " + message);
this.controller.set('loginFailed', true);
});
}
}
});
Upvotes: 0
Views: 1752
Reputation: 3368
all you need to do is changing the following line:
this.get('session').authenticate('authenticator:custom', credentials)
.then(function(){....}
to using fat arrow notation as follows:
this.get('session').authenticate('authenticator:custom', credentials)
.then(()=>{....}
so that this
context within the promise context will be your controller. See following for more about ES6 arrow functions.
Upvotes: 2
Reputation: 1298
It's based on my own code, so you might need to adapt it. But in your authenticator, your authenticate
function may look like this :
# authenticator
authenticate(credentials) {
const { identification, password } = credentials;
const data = JSON.stringify({
auth: {
email: identification,
password
}
});
const requestOptions = {
url: this.tokenEndpoint,
type: 'POST',
data,
contentType: 'application/json',
dataType: 'json'
};
return new Promise((resolve, reject) => {
ajax(requestOptions).then((response) => {
// Set your session here
}, (error) => {
run(() => {
reject(error);
});
});
});
},
Upvotes: 1