问题描述
在我的单页应用程序的所有控制器和范围内共享某些数据的最佳方式是什么?
What is the best way to share some data across all controllers and scopes of my Single page application ?
假设我有一小部分数据,我希望能够在任何地方访问,而且我不想每次需要时都查询数据库.
Let say i have a small set of data I want to be able to access everywhere, and I don't want to query the database every time I need it.
推荐答案
共享数据服务似乎是最适合您的情况的方法.有 $rootScope
作为全局范围,但是由于性能问题,$rootScope
不应该用于这样的事情.$rootscope
是 angular 摘要循环的一部分,所以当你向它添加一些东西时,你也添加了更多要检查的东西.因此,除非非常必要,否则不建议使用.
Shared data services seems to be the best aproach for your case. There is $rootScope
as a global scope, but, $rootScope
shoudn't be used for such thing due to performance issues. $rootscope
is part of angular digest cycle, so when you add something to it, you are also adding something more to be checked. Therefore, it's not recommended to use unless it's extremely necessary.
例如,对于简单的服务:
For example, for simple services:
app.service('SharedDataService', function () {
var Data = {
field1: 'qweqwe',
field2: '12312'
};
return Data;
});
对于具有异步操作的复杂服务:
For complex services with async operations:
app.service('SharedDataService', function () {
var self = this;
this.getData = function () {
if(self.cachedData){
return $q.resolve(self.cachedData);
}
return $http.get('my-data-url').then(function (response) {
self.cachedData = response.data;
return self.cachedData;
});
};
});
和控制器:
app.controller('MyController', function ($scope, SharedDataService) {
SharedDataService.getData().then(function (data) {
$scope.data = data;
});
});
这篇关于AngularJS:如何在我的 SPA 的所有页面和控制器之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!