Search code examples
phpangularjsangularjs-serviceangularjs-controllerdeferred

store php response in angularjs service, then get them in controller


So, I am new to angularjs. I want to use MVC structure. So, I was thinking that storing the response from php in my service, then use them in my controller.

Service:

(function () {
  angular.module('dataService').service("incidentService", function ($http) {
    var Data = [];

    return ({
        getData: __getData
    });


    function __getData() {
        return Data;
    }

    function __setData($http, $q) {
        var defer = $q.defer();
        $http.get('PHP/NAME.php',{cache : 'true'}).
        success(function(data){
            Data = data;
            console.log(Data);
            defer.resolve(data);
            defer.promise.then(function(data){
                Data = data;
                console.log(Data);
            });
        });
    }
})})();

Controller:

(function () {

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

 /** @ngInject */
 function Ctrl($scope, $http, $q,baConfig, incidentService) {

  incidentService.setData($http,$q)

  var DataSet = incidentService.getData();
  console.log(DataSet);
 }
})();

By doing this way, the problem is my dataSet does not get updated when the data array in my service is updated. I know that we can return a defer promise to controller to get the data, but can we set the data first in service, then use get method to use them?


Solution

  • OK, I think the biggest issue with why this doesn't work is because you're assigned the data returned by the $http call to nData rather than just Data.

    The next issue is that there's not a getMonthlyData method defined on the service.

    That being said, this looks overly complicated.

    Your service should look more like this:

    (function () {
      angular.module('dataService').service("incidentService", function ($http,$q) {
        var service    
        service.getData = __getData()
        return service
    
        function __getData() {
            if (!service.Data) {
            return $http.get('PHP/NAME.php',{cache : 'true'}).then( function(data) {
                service.Data = data
                return $q.when(service.Data)
            })} 
            else {
                 return $q.when(service.Data)
            } 
        }
    })})();
    

    Then in your controller you just get the data via incidentService.getData()