我目前正在阅读 ng-book,只是想知道这个与服务相关的代码示例是否是好的做法:
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.
我想知道,这样当您打开一个新标签时,用户名不会保留。为应用程序保持这种状态,使用localstorage/cookies不是更好吗?
这是一般的好做法吗?
最佳答案
你可以两者都做。将此类数据保存在服务中的私有(private)变量中可以将其隔离,您可以控制读/写以进行某种验证。这样,您就不允许在服务内部以外的任何地方修改数据。
您可以做的是在服务中添加一个保存函数,将所需数据保存在存储中,以及一个在 app.run 方法上调用的公共(public)调用函数。
您的服务:
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'
});
}
//Saves the data inside localStorage
var save = function() {
localStorage.setItem('githubData', guthubUserName);
}
// Return the service object with two methods
// events
// and setUsername
return {
events: function() {
return runUserRequest('events');
},
setUsername: function(username) {
githubUsername = username;
save(); // keeps the username always up to date
},
recall : function(){
githubUsername = localStorage.getItem('githubData');
}
};
});
你的 main.js: var app = app.module('yourGitHubApp', ['myApp.services'])
app.run(function(githubService){
githubService.recall();
})
因此每次应用程序重新加载时,localStorage 中的数据都会被刷新。
关于javascript - 服务中的 Angular 存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013529/