Reputation: 323
I'm using Ember.Service as a long-lived ember object cause I need it to be available in different parts of my application.
import Ember from 'ember';
export default Ember.Service.extend({
user:null,
updateActiveUser(user){
this.set('user',user);
},
getActiveUser(){
const user=this.get('user');
if(user){
return user;
}else{
return null;
}
}
});
On my component I'm asking for this user in this way: import Ember from 'ember';
export default Ember.Component.extend({
activeUser:Ember.inject.service('active-user'),
list: [],
selectedUser:null,
didReceiveAttrs() {
this._super();
this.set('list',this.get('model'));
const active=this.get('activeUser').getActiveUser();
if(active){
this.set('selectedUser',active);
}else{
this.set('selectedUser',this.get('model').objectAt(0));
}
},
actions:{
selectUser(user){
this.set('selectedUser',user);
this.get('activeUser').updateActiveUser(user);
}
}
});
My issue is that after I select a user and then I reload the page is not saving the last user selected and its showing the default user.
Upvotes: 3
Views: 1397
Reputation: 7671
(edited after the question has changed a bit)
You are trying to get the app state to persist on the client's browser, even after a page refresh.
I think you should look into using localStorage.
In your service do something like this:
import Ember from 'ember';
export default Ember.Service.extend({
user: null,
updateActiveUser(user){
this.set('user', user);
// persist the user's browser so it can be retrieved on reload
localStorage.setItem('user', JSON.stringify(user));
},
getActiveUser(){
var user = this.get('user');
if (user) {
return user;
} else {
// try to get the user from localStorage
var foundUser = JSON.parse(localStorage.user);
if (foundUser) {
this.set('user', foundUser);
return foundUser;
} else {
return null;
}
}
}
});
Lastly, why are you using const
? That is meant to be used if you are never going to change the variable. But it looks like the user is changed regularly. ES6 is supposed to throw an exception if you change a variable marked as const. const - MDN
Upvotes: 4
Reputation: 19789
You're not assigning the user but an undefined variable in your code
updateActiveUser(user){
this.set('user',kid);
}
Should be this.set('user', user);
UPDATE
The issue is that an Ember Service does not live through page reloads because all the JS gets thrown away and reloaded (your app included).
You can store the data from your service in the browsers local storage or something similar.
Upvotes: 2