简体   繁体   English

angularjs:如何一次加载远程通用数据并在控制器之间共享?

[英]angularjs: how to load remote common data once and share it across controllers?

In my angularjs app, I want to load just once a huge list of data, and share it across controllers. 在我的angularjs应用中,我只想加载一次庞大的数据列表,并在控制器之间共享。 So I have a factory that retrieve data over http: 所以我有一家工厂可以通过http:检索数据:

angular.module('app').factory('reportFactory', ['$http', function ($http) {
        var reportFactory = {};
        reportFactory.endPoint = 'ajax.php';
        reportFactory.getHugeData = function () {
            return $http.get(this.endPoint + '?query=CourseListQuery');
        };
        return reportFactory;
    }]);

I tried this: 我尝试了这个:

angular.module('app').factory('CommonData', ['reportFactory', function CommonDataFactory(reportFactory) {
    var data = {};
    reportFactory.getHugeData().then(function (response) {
        data.courses = response.data;
    }, function (error) {
    });
    return data;

}]);

but then when in my controller I tried to access log.warn(CommonData.courses); 但是当我在控制器中时,我试图访问log.warn(CommonData.courses); , I got undefined ,我undefined

I would like to store the result of that promise to get it available to all my angularjs app. 我想存储该承诺的结果,以使其可用于我的所有angularjs应用。

How to structure that and where to make the unique call that will retrieve data? 如何组织该结构以及在何处进行将检索数据的唯一调用?

Use a provider. 使用提供者。

angular.provider("CommonData", [function() {
    this.commonData = {};

    this.setCommonData = function(commonData) {
        this.commonData = commonData;
    };

    this.getCommonData = function() {
        return this.commonData;
    };
}]);

Then in the controller: 然后在控制器中:

angular.controller("ExampleController", ['CommonDataProvider', function(CommonDataProvider) {
    var commonData = CommonDataProvider.getCommonData();
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM