RSKMR RSKMR - 3 months ago 19
AngularJS Question

Angularjs + Promise

I am using Angularjs, I have two api in method in factory method. I tried to access that two method one by one. but its not working.

We need to first print test1 then print test2.

Controller code:

app.controlle("Test").function($scope, factoryMethod) {
factoryMethod.test1().then(function(data) {

console.log(data);
console.log("test1");

}).then(factoryMethod.test2().then(function(data) {
console.log(data);
console.log("test2");

})).catch(function(data) {
alert(data);
});
}


Factory code:

app.factory("factoryMethod", function (){
//code for test1
//code for test2
});


Currently the console log print the following order:
1. test2
2. test1

Expecting test1 and than test2

Answer

it can be done like this. look at snippet

var app = angular.module('myapp',[]);

app.factory("factoryMethod",['$q',function($q){
  
  var  test1 = function(){
     var deferred = $q.defer();
    
         deferred.resolve("test1");
          
          return deferred.promise;
    }
    
  var  test2 = function(){
      var deferred = $q.defer();
    
         deferred.resolve("test2");
          
          return deferred.promise;
    }
    
  return {
      test1 : test1,
      test2 : test2
    }
}]);

app.controller("Test",function($scope, factoryMethod){
  
  var promise =  factoryMethod.test1();
  
  promise.then(function(data){
  
    console.log(data);
    
    factoryMethod.test2().then(function(data){
    console.log(data);
        },function(error){
    console.log("error from test 2");
})
      },function(error){
   console.log("error from test 1")
})
   
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="Test">
  
</div>