AngularJS App: Load data from JSON once and use it in several controllers

ⅰ亾dé卋堺 提交于 2019-12-03 14:54:47

Try this to get JSON Data from a GET Link:

(function (app) {
    'use strict';

    app.factory('myService', MyService);

    MyService.$inject = ['$q', '$http'];

    function MyService($q, $http) {
        var data;

        var service = {
            getData: getData
        };

        return service;

        //////////////////////////////////////

        function getData(refresh) {
            if (refresh || !data) {
                return $http.get('your_source').then(function(data){
                    this.data = data;
                    return data;
                })
            }
            else {
                var deferrer = $q.defer();
                deferrer.resolve(data);
                return deferrer.promise;
            }
        }
    }

}(angular.module('app')));

Now you can add this dependency in your controller file and use:

myService.getData().then(function(data){
    //use data here 
}, function(err){
    //Handle error here
});

Initialize the promise once, and return a reference to it:

No need to initialize another promise. $http returns one.

Just tack a .then() call on your promise to modify the result

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

Edit: you may consider using $http cache instead. It can achieve the same results. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!