Angular js:如何进行工厂/服务方法的同步调用

时间:2016-07-13 07:23:27

标签: javascript jquery html angularjs

在朗姆酒方法中,我称之为工厂方法。当以秒为单位时,我传递第一种方法的输出。

在这种情况下如何同步执行这些方法。

mycontroller.js

(function () {
    "use strict";

 angular
    .module("autoQuote")
        //Do initalization on page load
       .run(["$log","$rootScope","$state","dtoResource","questionResource",function($log,$rootScope,$state,dtoResource,"questionResource") { 
          $rootScope.AutoQuote = dtoResource.rc1Step1DTO();
          $rootScope.questions = questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode);
          console.log($rootScope);
          $rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
            if (fromState.name === "") { 

            }
          });
        }])
}()); 

dtoresource.js

(function () {
    "use strict";

    angular
        .module("autoQuote")
        .factory("dtoResource",["$resource",dtoResource]);

    function dtoResource($resource)
    {
        console.log('here in dto process.');
        var prepareAutoQuoteDTO = {        
        postAutoQuoteObj         : getAutoQuoteObject(),  
       /*
       * store session info
       */
       rc1Step1DTO : function(){
        var emailId = 'test1@gmail.com';
        if (emailId && emailId != '' && emailId != 'Email Address'){
            var email           = new Email();
            email.EmailTypeCd   = 'PRIMARY';
            email.EmailAddress  = emailId;
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
        } 
       return prepareAutoQuoteDTO;
     }, 

     rc1Step2DTO :  function(){
        /*
        * Store Driver information into array object
        * Collect driver info into local array and then reassign them to actual DTO object
        */
        this.postAutoQuoteObj.SessionInfo.UseExistingSession = false;
        this.postAutoQuoteObj.SessionInfo.PageName           = 'driver';
        this.postAutoQuoteObj.SessionInfo.PreviousPageName   = 'cars';
        //this.setCLK();
        return prepareAutoQuoteDTO;            
     }
    };
  return prepareAutoQuoteDTO;
}
}());

questionResource.js

(function () {
    "use strict";

    angular
    .module("autoQuote")
    .factory("questionResource",["$resource","$http","$state",questionResource]);

    function questionResource($resource,$http,$state)
    {   
        return{
         getQuestions : function(stateCode) {
             var userState = stateCode != "" ? stateCode : 'CA';
             $http.get('assets/themes/easyquote/js/questions/'+userState+'.json')
             .then(function(response) {
                return response.data;  
            }); 
        }
       }
    }
}()); 

在autoQuotecontroller下面的行shoud执行一个接一个

$rootScope.AutoQuote = dtoResource.rc1Step1DTO();
          $rootScope.questions = questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode);

1 个答案:

答案 0 :(得分:1)

你需要利用承诺。工厂中的每个方法都应该返回一个承诺。您可以使用$q来执行此操作。

第1步

$q注入您的工厂。例如让我们在dtoResource工厂这样做

    angular
     .module("autoQuote")
     .factory("dtoResource",["$resource",'$q', dtoResource]);

    function dtoResource($resource, $q)
    .....

第2步

让方法返回这样的承诺

 rc1Step1DTO : function(){
     var deferred = $q.defer();
      var emailId = 'test1@gmail.com';
      if (emailId && emailId != '' && emailId != 'Email Address'){
        var email           = new Email();
        email.EmailTypeCd   = 'PRIMARY';
        email.EmailAddress  = emailId;
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
       deferred.resolve(prepareAutoQuoteDTO);
       } 
      return deferred.promise;
   }
  

第二个函数(prepareAutoQuoteDTO)所需的参数需要传递给deferred.resolve,以便它可用于链中的下一个函数

第3步 转换所有工厂方法(需要同步执行)以返回上面的承诺

第4步  像这样调用控制器中的那些方法

 dtoResource.rc1Step1DTO()
 .then(questionResource.getQuestions)
 .then(function(){
   console.log('This should be printed after the above methods are done     executing');
  })
.fail(function(reason){
  console.log(reason + ' this is the reason that your code failed. The reason comes from a defered.reject from your chained methods');
 });
  

<强>记住

     
      
  • 代码的所有可能分支必须解决或拒绝承诺
  •   
  • 使用deferred.resolve或reject
  • 将参数传递给链接函数   
  • fail步骤
  • 中处理控制器中的故障情况   
  • 明智地使用承诺
  •