WaterBoy
WaterBoy

Reputation: 709

How to wait for a result from a service in angularjs

I have 2 services. One service (TimeEventService) saves data to a database table. The other service (ReportingService) is a wrapper for TimeEventService and provides functionality to controllers.

I need the ReportingService to wait for a 'saved' response from the TimeEventService. What is the best and simplest way to do this please.

TimeEventService code:

angular.module('TimeEventServiceMod', ['ngResource']).
factory('TimeEventService', function(TestTimeEventService,$filter) {

	    var timeEventData = {
		savedEvent:null
	};


	timeEventData.newEvent = function(ataskSequenceId,eventNumber){
		var newEvent = new TestTimeEventService();
		newEvent.tasksequenceid = ataskSequenceId;
		newEvent.event = eventNumber;
		newEvent.timeofevent = new Date();

	    newEvent.$save(function(){
	     	timeEventData.newEvent=newEvent;
	      	console.log('saved  event OK: ' + angular.toJson(timeEventData.newEvent));
	      	return timeEventData;
	    },function (errorResponse) {
	        // failure callback
	        console.log('error saving Event and new status to  db:' + angular.toJson(errorResponse));
	    });
	};

ReportingService code:

angular.module('ReportingServiceMod', ['ngResource','TimeEventServiceMod']).
factory('ReportingService', function(TimeEventService) {

    var reportData = {
    	lastTimeEventId:-1
	};
	var timeEventData = TimeEventService;

	//the public test events
	reportData.newEvent_testStart = function(ataskSequenceId){newEvent(ataskSequenceId,10)};

	newEvent = function(ataskSequenceId, eventid){
		
		timeEventData = TimeEventService.newEvent(ataskSequenceId,eventid);
		if (timeEventData.savedEvent!=null)
			reportData.lastTimeEventId = timeEventData.savedEvent.id;
		console.log('saved time event id:' + reportData.lastTimeEventId);
	};



     return reportData;
  })

Note the line (if (timeEventData.savedEvent!=null)) does not work as the object has not yet been saved.

Upvotes: 0

Views: 44

Answers (1)

Nikhil Mohanan
Nikhil Mohanan

Reputation: 1260

angular
    .module('myApp',[])
    .run(function($rootScope){
        $rootScope.title = 'myTest Page';
    })
    .controller('testController', ['$scope','testFactory1','testFactory2', function($scope, testFactory1, testFactory2){

        testFactory1.firstCall()
         .then(function(reply){
           if(reply){
            testFactory2.secondCall()
             .then(function(reply){
               if(reply){

               }
             },function(err){
               console.log("there was a error", err);
             });
           }
         },function(err){
           console.log("there was a error", err);
         });
    }]).factory('testFactory1',['$http','$q', function($http, $q){
      var ser1 = {
        firstCall : firstCall,
      }
      return ser1;

      function firstCall(){

        var first = $q.defer();
         $http.get(....)
          .then(function(result){
            first.resolve(result.data);
          },function(error){
            first.reject(error.data);
          })
          return first.promise;
      }

    }]).factory('testFactory2',['$http','$q', function(){
      var ser2 = {
        secondCall : secondCall,
      }
      return ser2;

      function secondCall(){

        var second = $q.defer();
         $http.get(....)
          .then(function(result){
            second.resolve(result.data);
          },function(error){
            second.reject(error.data);
          })
          return second.promise;
      }
    }]);

Explanation :

Why dont you call services from controllers.
here we have two facotries `testFactory1` and `testFactory2` and each have a http call.
So you can call these from controllers one after another.

in 'testController'  you are calling 'firstCall' http function first, and on its sucess we are making 'secondCall',
We can use $q service to wait for secondCall to make till firstCall finishes.

Upvotes: 1

Related Questions