user7736786
user7736786

Reputation:

Angular1.6 Factory

Hii I m using following code. I am reading a json file name is "users.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a factory for this. but in factory when i read data from that json file through $http.get() and in return when i call that service method in my controller and it returns Object { $$state: Object }

app.factory('AboutFactory',['$http',function ($http) {
    return {
        getter: function () {
            return $http({
                method : 'GET',
                url : '/home/penguin/Modeles/users.json',
                cache : true
            })
            .then(function (response) {
                return response.data
            })
        }         
    }
}])

Upvotes: 0

Views: 71

Answers (3)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27242

Try this approach. It will work as per your expectation.

  • Read JSON file in controller through $http service as it is works fine.
  • For sharing the response data from one controller to another you can create a service and store the data into that service.

Service :

app.service('setGetData', function() {
  var data = '';
    getData: function() { return data; },
    setData: function(requestData) { data = requestData; }
});

Controllers :

app.controller('myCtrl1', ['setGetData',function(setGetData) {

  // To set the data from the one controller
  var data = 'Hello World !!';  
  setGetData.setData(data);

}]);

app.controller('myCtrl2', ['setGetData',function(setGetData) {

  // To get the data from the another controller  
  var res = setGetData.getData();
  console.log(res); // Hello World !!

}]);

Here, we can see that myCtrl1 is used for setting the data and myCtrl2 is used for getting the data. So, we can share the data from one controller to another controller like this.

Upvotes: 0

cnorthfield
cnorthfield

Reputation: 3501

That's because the $http service returns a promise as mentioned in the documentation:

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can think of a promise as if you give a top secret message to someone to deliver personally to a friend, then when delivered, report back to you with a message back from your friend.

  1. You provide the message (the request object) to the person so that they can attempt to make the delivery of the message (send the request).

  2. The attempted delivery has taken place (the request has been sent), it either:

    • a) was delivered successfully (successful response) or
    • b) your friend was not in so the letter could not be delivered (non success response).
  3. You can then act depending on the response you get back

    • a) Message was delivered (it was a successful request) and you got a letter back (do something with the response) or
    • b) Message failed to get delivered (request wasn't successful), so you can maybe try again later or do something else as you don't have the information you requested

Here is an example of using the $http service with the $q service:

// app.js
(function() {

  'use strict';

  angular.module('app', []);

})();

// main.controller.js
(function() {

  'use strict';

  angular.module('app').controller('MainController', MainController);

  MainController.$inject = ['AboutFactory'];

  function MainController(AboutFactory) {

    var vm = this;

    AboutFactory.getter().then(function(data) {

      // do something with your data
      vm.data = data;

    }, function(error) {

      // give the user feedback on the error

    });

  }

})();


// about.service.js
(function() {

  'use strict';

  angular.module('app').factory('AboutFactory', AboutFactory);

  AboutFactory.$inject = ['$http', '$q']

  function AboutFactory($http, $q) {

    var service = {
      getter: getter
    };

    return service;

    function getter() {

      // perform some asynchronous operation, resolve or reject the promise when appropriate.
      return $q(function(resolve, reject) {

        $http({
          method: 'GET',
          url: 'https://httpbin.org/get',
          cache: true
        }).then(function(response) {

          // successful status code

          // resolve the data from the response
          return resolve(response.data);

        }, function(error) {

          // error

          // handle the error somehow

          // reject with the error
          return reject(error);

        });

      });

    }
  }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<div ng-app="app" ng-controller="MainController as MainCtrl">

  <pre>{{MainCtrl.data | json}}</pre>

</div>

Upvotes: 0

Kingmaker
Kingmaker

Reputation: 519

Result of getter function is a promise. so you should use it like this:

AboutFactory.getter().then(function(res)
{
   console.log(res);
});

Upvotes: 2

Related Questions