Share async data between controllers without making multiple requests

后端 未结 4 1221
盖世英雄少女心
盖世英雄少女心 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:34

    I found the way not sure weather it is a best approach to do it or not.

    In HTML

    
      
    {{user.title}}

    {{user.title}}

    In Javascript

     var app = angular.module('myApp', []);
       app.controller('ctrl', function($scope, $http, userService) {
          userService.getUser().then(function(user) {
            $scope.user = user;
          });
        });
    
       app.controller('ctrl2', function($scope, $http, userService) {
          userService.getUser().then(function(user) {
            $scope.user = user;
          });
        });
    
       app.factory('userService', function($http, $q) {
        var promise;
        var deferred = $q.defer();
          return {
            getUser: function() {
              if(!promise){     
              promise = $http({
                  method: "GET",
                  url: "https://jsonplaceholder.typicode.com/posts/1"
                }).success(function(res) {
                    data = res.data;
                  deferred.resolve(res);
                })
                .error(function(err, status) {
                  deferred.reject(err)
                });
              return deferred.promise;
              }
              return deferred.promise;
            }
          }
        });
    

    This will exactly make only 1 HTTP request.

提交回复
热议问题