I'm currently reading ng-book, and just wondered if this code example related to services is good practice:
To share data across controllers, we need to add a method to our service that stores the username. Remember, the service is a singleton service that lives for the lifetime of the app, so we can store the username safely inside of it.
angular.module('myApp.services', [])
.factory('githubService', function($http) {
var githubUrl = 'https://api.github.com',
githubUsername;
var runUserRequest = function(path) {
// Return the promise from the $http service
// that calls the Github API using JSONP
return $http({
method: 'JSONP',
url: githubUrl + '/users/' +
githubUsername + '/' +
path + '?callback=JSON_CALLBACK'
});
}
// Return the service object with two methods
// events
// and setUsername
return {
events: function() {
return runUserRequest('events');
},
setUsername: function(username) {
githubUsername = username;
}
};
});
Now, we have a setUsername method in our service that enables us to set the username for the current GitHub user.
I wonder, this way the username doesn't persist when you open a new tab. Isn't it better to use localstorage / cookies to keep this kind of state for the application?
Is this good practice in general?
localStorageor cookies would be better.