"how to get data from an api in a angular service and store it to be used by anyone in the future" Code Answer

1

here is a sample example on how to use factory for sharing data across the application.

lets create a factory which can be used in entire application across all controllers to store data and access them.

advantages with factory is you can create objects in it and intialise them any where in the controllers or we can set the defult values by intialising them in the factory itself.

factory

app.factory('shareddata',['$http','$rootscope',function($http,$rootscope){

    var shareddata = {}; // create factory object...
    shareddata.appname ='my app';
    return shareddata;
}]);

service

app.service('auth', ['$http', '$q', 'shareddata', function($http, $q,shareddata) {
   this.getuser = function() {

            return $http.get('user.json')
              .then(function(response) {
                  this.user = response.data;
                  shareddata.userdata = this.user; // inject in the service and create a object in factory ob ject to store user data..
                  return response.data;
              }, function(error) {
                  return $q.reject(error.data);
              });

    };

}]);

controller

var app = angular.module("app", []);
app.controller("testcontroller", ["$scope",'shareddata','auth',
  function($scope,shareddata,auth) {

    $scope.user ={};
   // do a service call via service and check the shared data which is factory object ...
   var user = auth.getuser().then(function(res){
       console.log(shareddata);
       $scope.user = shareddata.userdata;// assigning to scope.
   });


  }]);

in html

<body ng-app='app'>
    <div class="media-list" ng-controller="testcontroller">

       <pre> {{user | json}}</pre>

    </div>

</body>
By Manish Saraf Bhardwaj on September 9 2022

Answers related to “how to get data from an api in a angular service and store it to be used by anyone in the future”

Only authorized users can answer the Search term. Please sign in first, or register a free account.