Data from $http request to Service

Hello,

I have a form in my app which sends two dates to my php-script. This script collects the requests that are between the given dates. Now, I have an array with the requests in json-objects. Works perfect.

What I would like to do is sending these requests to a service to be able to have a master and detail page of these requests.

So, I have the date in my controller. But I would like it to have in a service.

The data is in $scope.foundRequests:

   $http.post("http://url/to/searchreports.php", data,{"startdate": $scope.searchData.startdate, "enddate": $scope.searchData.enddate})
            .success(function(data){
            	if (!data) {
    			    $scope.loadingIndicator = $ionicLoading.show({
    				    content: 'Loading Data',
    				    animation: 'fade-in',
    				    showBackdrop: false,
    				    maxWidth: 200,
    				    showDelay: 100
    			    });
    			    
    			    $timeout(function() {
    				    console.log("something is wrong");
    			        $ionicLoading.hide();
    			    }, 1000);
            	} else {
    	            $scope.foundRequests = data;
    	            console.log($scope.foundRequests);
    
    		        $scope.loadingIndicator = $ionicLoading.show({
    				    content: 'Loading Data',
    				    animation: 'fade-in',
    				    showBackdrop: false,
    				    maxWidth: 200,
    				    showDelay: 100
    			    });
    		        
    		        $timeout(function() {
    			        $ionicLoading.hide();
    			        $scope.searchData.startdate = "";
    		        	$scope.searchData.enddate = "";
    			    }, 1000); 
    			}
            })

Is not very clear, I think this http code must be in a service ‘factory’ as good practice.
And this service can be consumed from any controller and keep the result as ‘cached data’ as it has single instance.

See: Sharing Data Between Controllers

This will dapender of your case, there are numerous ways of how to approach.

A scribble:

angular.module('app')
.controller('myListController', ['$scope', 'myDataService', function($scope, myDataService) {
	
	myDataService.dataCacheReady().then(function(){
		// Auto update if other controller get data and change 'cachedData', sharing observable reference
		$scope.myListData = myDataService.cachedData;
	});

}])
.controller('myMainCtrl', ['$scope','$ionicLoading','myDataService', function($scope, $ionicLoading, myDataService) {

	// Initialize data on some point
	requestData();

	function requestData() {
			return myDataService.initData('<dataParam>', '<startdate>', '<enddate>')
				.then(function (data) {
					if (!data) {
	    			    $timeout(function() {
	    				    console.log("something is wrong");
	    			        $ionicLoading.hide();
	    			    }, 1000);
	            	} else {
	    	            $scope.foundRequests = data;
	    	            console.log($scope.foundRequests);
	    		        $timeout(function() {
	    			        $ionicLoading.hide();
	    			        $scope.searchData.startdate = "";
	    		        	$scope.searchData.enddate = "";
	    			    }, 1000); 
	    			}
				}, 
				function (err){
					// error
				})
				.finally(function (){
					// Fire on success or error
					$scope.loadingIndicator = $ionicLoading.show({
	    				    content: 'Loading Data',
	    				    animation: 'fade-in',
	    				    showBackdrop: false,
	    				    maxWidth: 200,
	    				    showDelay: 100
	    			    });
				});
		}

}])
.factory('myDataService', [
	'$http', '$q', function($http, $q) {
		var dataCacheReadyDeferred = $q.defer();
		var cachedData = null;

		var service = {
			initData: initData,
                    dataCacheReady: dataCacheReady,
			cachedData: cachedData // Shared data, in not init is null
		};

		return service;

		function dataCacheReady() {
            return dataCacheReadyDeferred.promise;
        }

		function initData(dataParam, startdate, enddate) {

			if(!startdate || !enddate){
				return $q.when(null);
			}

			var options = {"startdate": startdate, "enddate": enddate};

			return $http.post("http://janheyms.nl/absencemanagement/searchreports.php", dataParam, options)
	            .success(function(data, status) {
	            	if (data) {
	            		dataCacheReadyDeferred.resolve(true);
	            		angular.copy(data, cachedData);
	            	}
	            });
		}

}]);    

try this pen, i think it solves your problem and sets up a service, I have simplified the code a bit

Works great!

Now, I would like to change the static values ‘1-1-2000’ and ‘1-1-2015’ to the dynamic values that I put in the date-fields. These are named searchData.startdate and searchData.enddate and attached to the field with ng-model.

Thanks in advance.

can u try to puta pen together?

Not at the moment, sorry. My HTML-code is like this:

<ion-view title="Search">
  <ion-header-bar>
    <h1 class="title">Request form</h1>
  </ion-header-bar>
  <ion-content>
    <form ng-submit="requestData()">
      <div class="list">
	      	<div class="item item-divider">
			    Search between dates
			</div>
			<label class="item item-input">
			  <span class="input-label">Starts</span>
			  <input type="date" ng-model="searchData.startdate">
			</label>
			<label class="item item-input">
			  <span class="input-label">Ends</span>
			  <input type="date" ng-model="searchData.enddate">
			</label>
      </div>
    </form>
    
    <div class="item item-divider">
		Found requests
	</div>
  <ion-list>
      	<ion-item class="item item-avatar" ng-repeat="request in foundRequests | orderBy:'date'" href="#/app/detail/{{request.id}}">
				<img class="imgavatarbig" ng-src="{{request.picture}}">
				<h3>{{request.firstname}} {{request.lastname}}</h3>
				<p class="requestp">{{request.reason}}</p>
				<p class="requestp">{{request.notes}}</p>
				<span class="rightrequest">
					<h4>{{request.status}}</h4>
				</span>
      	</ion-item>
      	<ion-item ng-if="foundRequests.length == 0">
	      	No results found
      	</ion-item>
      </ion-list>
  </ion-content>
      <ion-footer-bar>
        <div class="button-bar">
          <button class="button button-width-red ion-checkmark" ng-click="requestData()"></button>
        </div>
    </ion-footer-bar>
</ion-view>

Which means: pressing the button, the requestData() function is called and the values of searchData.startdate and searchData.enddate are submitted instead of the static values 1-1-2000 and 1-1-2015

So, instead of this line:

return myDataService.initData({}, ‘1-1-2000’, ‘1-1-2015’)

I think it has to be something like this:

return myDataService.initData({}, $scope.searchData.startdate, $scope.searchData.enddate)

But this doesn’t work.

Any ideas?

Thanks,

Jan

startdate and enddate are “Date objects” you will have to inject $filter, and use $filter(‘date’) to get that in the format you wanted

https://docs.angularjs.org/api/ng/filter/date

Okay,

The list does work! But now I have to go from this list to the detailpage. How to get the right data to this page?