AngularJS:如何在SPA的所有页面和控制器上共享数据? [英] AngularJS: How do I share data accross all pages and controller of my SPA?

查看:118
本文介绍了AngularJS:如何在SPA的所有页面和控制器上共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单页应用程序的所有控制器和范围内共享某些数据的最佳方法是什么?

What is the best way to share some data across all controllers and scopes of my Single page application ?

让我说我想在任何地方都可以访问一小部分数据,并且我不想每次都需要查询数据库。 / p>

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 是角度摘要循环的一部分,因此,当向其中添加内容时,还会添加更多要检查的内容。因此,除非非常必要,否则不建议使用。

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.

例如,对于简单服务:

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的所有页面和控制器上共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆