javascript - AngularJS 应用程序 : Load data from JSON once and use it in several controllers

标签 javascript angularjs ng-view

我正在开发一个使用 AngularJS 作为框架的移动应用程序,目前我的结构与此类似:

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'homeCtrl'
        })

        .when('/one', {
            templateUrl : 'pages/one.html',
            controller  : 'oneCtrl'
        })

        .when('/two', {
            templateUrl : 'pages/two.html',
            controller  : 'twoCtrl'
        });
}]);

app.controller('homeCtrl', ['$scope', function($scope) {

}]);

app.controller('oneCtrl', ['$scope', function($scope) {

}]);

app.controller('twoCtrl', ['$scope', function($scope) {

}]);

然后我用 ng-view 显示内容:

<div class="ng-view></div>

一切正常,但我需要从 JSON 文件加载数据以填充应用程序的所有内容。我想要的是制作一个 AJAX 调用仅一次,然后通过我所有不同的 Controller 传递数据。在我的第一次尝试中,我想创建一个在其中包含 $http.get() 的服务,并将其包含在每个 Controller 中,但它不起作用,因为它每次都会发出不同的 ajax 请求注入(inject)并使用该服务。由于我是 angular 的新手,我想知道什么是最好的方法或更“Angular 方法”来实现这一目标而不会搞砸。

编辑:我正在添加服务代码,这只是一个简单的$http.get请求:

app.service('Data', ['$http', function($http) {
    this.get = function() {
        $http.get('data.json')
        .success(function(result) {
            return result;
        })
    }
});

最佳答案

初始化 promise 一次,并返回对它的引用:

无需初始化另一个 promise 。 $http 返回一个。

只需添加一个 .then() 调用你的 promise 来修改结果

angular.module('app', [])
  .service('service', function($http){
    this.promise = null;
    function makeRequest() {
         return $http.get('http://jsonplaceholder.typicode.com/posts/1')
             .then(function(resp){
                  return resp.data;
             });
    }
    this.getPromise = function(update){
      if (update || !this.promise) {
         this.promise = makeRequest();
      }
      return this.promise;      
    }
  })

Codepen example

编辑:您可以考虑改用 $http 缓存。它可以达到相同的结果。 From the docs :

If multiple identical requests are made using the same cache, which is not yet populated, one request will be made to the server and remaining requests will return the same response.

关于javascript - AngularJS 应用程序 : Load data from JSON once and use it in several controllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30784714/

相关文章:

javascript - 2 个用于打开 URL 的下拉菜单

javascript - React js从事件中调用函数

javascript - 调用指令 Controller 内的函数

javascript - AngularJS:自定义指令内的 ngView

javascript - ng-view 不遵循 1 个 View 的 CSS

javascript - 如何在 UI 中使用 foreach 计算可观察数组?

javascript - Chart.js - 折线图 : draw points between grid lines

javascript - 为什么下面的代码中没有定义$scope

angularjs - Angular - Material - 测试 - $mdSidenav

AngularJS一页中有多个模板