AngularJS: How do I share data accross all pages and controller of my SPA?

半世苍凉 提交于 2019-12-11 04:29:53

问题


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.


回答1:


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;
        });
    };
});

And the controller:

app.controller('MyController', function ($scope, SharedDataService) {
    SharedDataService.getData().then(function (data) {
        $scope.data = data;
    });
});



回答2:


The data to be stored in $rootscope variable

(or)

data to be stored in services




回答3:


Best to use service say commonService and after getting data from database store on a variable inside the service like this

this.dbDataSearch = function(parameters){
  // Search record from database
  this.resultData = data;
}

In Controller 1:

$scope.data = commonService.resultData;

In Controller 2:

$scope.data = commonService.resultData;

In Controller n:

$scope.data = commonService.resultData;



回答4:


In angularJS you can perform this operation in different ways. either you can use $rootscope or you can broadcast data or you can use services or factories.

But the bet preferred way is to use services. First thing is it's easy. You can use the same service on every controller to access the data.

If you want to know more about angularjs services please check below link.

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/



来源:https://stackoverflow.com/questions/40087220/angularjs-how-do-i-share-data-accross-all-pages-and-controller-of-my-spa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!