带有同步Http调用的AngularJS承诺

时间:2019-02-26 02:06:10

标签: angularjs http synchronous

在进行多个同步http调用时,我的一个控制器中没有调用then函数。

在下面的代码中,我的控制器中的console.log(data)语句未在执行,因为该控件从未使用过then函数。

********************控制器文件

function MyController($scope, $location, $timeout) {

    function submit($event) {
      Myservice.getDetails(productid).then(function(data){
        console.log(data) 
      });
    } 


angular.module('myModule')
    .controller('MyController', MyController);
})(window.angular);

****************** MyService

(function (angular, mySecondService) {
  'use strict';

  function MyService($http, $q, $log, $location, mySecondService{

    function getDetails(pId) {
      byodCheckerData = [];
      mySecondService.httpTkn().then(function(Tkn){
          var request = {
            method: 'GET',
            url: 'getDetails',
            headers: {auth: Tkn},
            params: {Id:pId}
          };

          return $http(request).then(function(resp){
            return resp;
          })                
      })              
    }; 

    return {
      getDetails: getDetails;
  }

angular.module('myModule')
.factory('MyService', MyService);

})(window.angular);

**************************************** MySecondservice

(function (angular) {
  'use strict';
  function mySecondService($log, $http, $q) { 
    var ts = this;
      function httpTkn(){
          defer = $q.defer();
          var authReq = {
            method: 'GET',
            url: 'getTkn'
          };
         return $http(authReq).then(function (response) {
              defer.resolve(response.data.tkn
        return response.data.tkn;
            },
            function (error) {

              return error;
            });
      };


    ts.httpTkn = httpTkn;
  }

  angular.module('myModule')
    .service('mySecondService', mySecondService);

})(angular);.

1 个答案:

答案 0 :(得分:-1)

您可以尝试以下代码:

function getDetails(pId) {
    var defered = $q.defer();
    byodCheckerData = [];
    mySecondService.httpTkn().then(function(Tkn) {
        var request = {
            method: 'GET',
            url: 'getDetails',
            headers: { auth: Tkn },
            params: { Id: pId }
        };

        $http(request).then(function(resp) {
            defered.resolve(resp);
        });
    });
    return defered.promise;
}

请注意,您需要返回Promise,以便在解析$http值时该函数起作用