Share async data between controllers without making multiple requests

后端 未结 4 1329
盖世英雄少女心
盖世英雄少女心 2021-02-14 20:21

I\'m trying to make a single $http request to get one of my JSON files and use the data across all my controllers.

I saw on egghead.io how to share data acr

4条回答
  •  半阙折子戏
    2021-02-14 20:47

    I like to store my data in the service, and return a promise to the controllers, because usually you need to deal with any errors there.

    app.factory('Data', function($http, $q) {
       var data = [],
           lastRequestFailed = true,
           promise;
       return {
          getApps: function() {
             if(!promise || lastRequestFailed) {
                // $http returns a promise, so we don't need to create one with $q
                promise = $http.get('apps.json')
                .then(function(res) {
                    lastRequestFailed = false;
                    data = res.data;
                    return data;
                }, function(res) {
                    return $q.reject(res);
                });
             }
             return promise;
          }
       }
    });
    
    .controller('appInstallerListCtrl', ['$scope','Data',
    function($scope, Data) {
        Data.getApps()
        .then(function(data) {
            $scope.data = data;
        }, function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else { 
                // probably deal with these errors differently
            }
        });
    }]);
    

    Any callbacks that are registered after a promise has been resolved/rejected will be resolved/rejected immediately with the same result/failure_reason. Once resolved/rejected, a promise can't change (its state). So the first controller to call getApps() will create the promise. Any other controllers that call getApps() will immediately get the promise returned instead.

提交回复
热议问题