【问题标题】:angularjs: how to load remote common data once and share it across controllers?angularjs:如何一次加载远程公共数据并在控制器之间共享?
【发布时间】:2017-08-22 20:10:50
【问题描述】:

在我的 angularjs 应用程序中,我只想加载一个巨大的数据列表,并在控制器之间共享它。 所以我有一个通过 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;
    }]);

我试过这个:

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

}]);

但是当我在我的控制器中尝试访问log.warn(CommonData.courses); 时,我得到了undefined

我想存储该承诺的结果,以使其可用于我的所有 angularjs 应用程序。

如何构建该结构以及在何处进行检索数据的唯一调用?

【问题讨论】:

  • 使用工厂中的函数获取data.courses
  • 您定义了“getHugeData”,但您调用了“getCourseList”。
  • @Ramsing Nadeem:这是在本网站上发布之前的拼写错误。固定的。谢谢。
  • @Ramsing Nadeem:你能提供一个详细的sn-p吗?
  • 不知道你的代码长什么样;在这里分享一个Plunker;应该调试它。

标签: javascript angularjs angularjs-scope


【解决方案1】:

使用提供者。

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

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

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

然后在控制器中:

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

【讨论】:

    猜你喜欢
    • 2015-12-15
    • 2014-03-22
    • 2013-05-28
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多