如何实现angularjs异步?

时间:2017-05-24 11:47:17

标签: javascript angularjs

我正在使用AngularJS v1.5.8,我的要求是,当我点击“下一步”按钮时,它会显示“正在处理...”'在完成操作之前,在内部按钮作为文本,我已将$ q与我的服务包括在内以获得异步设施,但无法正常工作。请看下面的代码。

服务

mainApp.factory('PINVerificationServices', ['$http', '$rootScope','$q', function ($http, $rootScope) {
    return {
        IsPermitted: function (param) {
            return $q($http({
                url: '/Api/ApiPINVerification/IsPermitted/' + param,
                method: 'POST',
                async: true
            }));
        }
    };
}]);

控制器

mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
    $scope.SubmitText = "Next";

    $scope.Next = function () {
    $scope.SubmitText = "Processing...";
    PINVerificationServices.IsPermitted($scope.PIN).then(function (result) {
         $scope.SubmitText = "Next";
    });
  }
}

HTML

  <div class="list-group list-group-sm">
    <div class="list-group-item">
        <input class="form-control" ng-model="PIN" placeholder="PIN" required id="PIN" name="PIN" type="text" />
    </div>
  </div>
  <button type="submit" ng-click="Next()">{{SubmitText}}</button>

2 个答案:

答案 0 :(得分:1)

试试这个:

 return $http({
                method: 'POST',
                url: '/Api/ApiPINVerification/IsPermitted/' + param
        });

答案 1 :(得分:0)

进行以下更改(根据您对嵌套$http的要求)。

工厂中仅使用$http,也不需要$rootScope,它应该是这样的:

    mainApp.factory('PINVerificationServices', ['$http', function ($http) {
        return {
               IsPermitted: function (param) {
                return $http({
                    url: '/Api/ApiPINVerification/IsPermitted/' + param,
                    method: 'POST'
                   });
                },

               GetStudentInformationByPIN : function () {
                return $http({
                    url: '/Api/ApiPINVerification/GetStudentInformationByPIN /',//your api url
                    method: 'GET'
                    });
               }
          };
    }]);

控制器中使用$q.all()

       mainApp.controller('PINVerificationController', function ($scope, $rootScope, $state, $window,$q, PINVerificationServices) {
       $scope.SubmitText = "Next";
       $scope.Next = function () {
            $scope.SubmitText = "Processing...";                      
            $q.all([PINVerificationServices.IsPermitted($scope.PIN),
            PINVerificationServices.GetStudentInformationByPIN($scope.PI‌N), 
             //other promises
            ]).then(function (result) {
                     if(result[0].data){
                         $scope.SubmitText = "Next";
                     }
                     if(result[1].data){
                         // studentdata response handling
                     }
                    });
            }
        }