代码之家  ›  专栏  ›  技术社区  ›  Chris

异步执行函数的angularjs

  •  0
  • Chris  · 技术社区  · 7 年前

    我有一个控制器,它将执行传递给工厂--controller.getcustomerbyid->factory.getcustomerbyid。在本例中,factory函数通过mvc/angular.$http.post发布和检索数据。一切正常,但我的控制器函数中的后续操作在.post完成之前执行。

    我试过使其中一个或两个异步/等待,但我想我不知道如何做到这一点。我在这里和其他地方都试过不少例子,但都不走运。

    我有一个按钮调用setOrderFromGrid,它调用getCustomerByID。我认为让controller.getcustomerbyid成为一个异步函数是最好的方法,但是我不能让它工作。

    angular.module('aps').factory('TechSheetFactory', 
    function($http) {
        return {
            //The ajax that is called by our controller
            ITS: function(onSuccess, onFailure) {
                const rvtoken = $("input[name='__RequestVerificationToken']").val();
                $http({
                    method: "post",
                    url: "/DesktopModules/MVC/TechSheetMaint/TechSheet/InitializeNew",
                    headers: {
                        "ModuleId": moduleId,
                        "TabId": tabId,
                        "RequestVerificationToken": rvtoken
                    }
                }).then(onSuccess).catch(onFailure);
            },
    
    
            saveTechSheetAng: function(onSuccess, onFailure, techSheetInfo) {
                alert(JSON.stringify(techSheetInfo));
                const rvtoken = $("input[name='__RequestVerificationToken']").val();
                $http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/SaveTechSheetAng",
                    JSON.stringify(techSheetInfo),
                    {
                        headers: {
                            "ModuleId": moduleId,
                            "TabId": tabId,
                            "RequestVerificationToken": rvtoken,
                            'Content-Type': 'application/json'
                        }
                    }).then(onSuccess).catch(onFailure);
            } ,
    
            getCustomerById: function(onSuccess, onFailure, customerSearchString) {
                alert('factory getcustomerbyid: ' + customerSearchString);
                const rvtoken = $("input[name='__RequestVerificationToken']").val();
                $http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/GetCustomerById",
                    {custId:customerSearchString},
                    {
                        headers: {
                            "ModuleId": moduleId,
                            "TabId": tabId,
                            "RequestVerificationToken": rvtoken,
                            'Content-Type': 'application/json'
                        }
                    }).then(onSuccess).catch(onFailure);
            }
    
    
        };
    });
    
    angular.module('aps').controller('TechSheetCtl', ['TechSheetFactory','$scope', '$rootScope', '$http', '$interval', '$modal', '$log','uiGridConstants', 
    function (TechSheetFactory,$scope, $rootScope, $http, $interval, $modal, $log) {
    
    
    /* -----------------SaveTechSheet ------------*/
        $scope.saveTechSheet = function() {
            if (!$scope.dvTechSheet.$valid) {
                $scope.Message = "Form not complete.";
                $scope.Status = false;
                $scope.showErrors=true;
                return;
            }
            alert($scope.TechSheetInfo.Customer.CustomerID);
            if (JSON.stringify($scope.TechSheetInfo.Customer) !== JSON.stringify($scope.TechSheetInfoStatic.Customer) &&
                $scope.TechSheetInfo.Customer.CustomerID !== 0) {
                if (confirm("You've made changes to this Customer. Save them?") !== true) {
                    return;
                }
            }
    
            if (JSON.stringify($scope.TechSheetInfo.WorkOrder) !== JSON.stringify($scope.TechSheetInfoStatic.WorkOrder) &&
                $scope.TechSheetInfo.WorkOrder.WorkOrderID !== 0) {
                if (confirm("You've made changes to this Work Order. Save them?") !== true) {
                    return;
                }
            }
            successFunction = function(response) {
                var data = response.data.Data;
                alert(data);
                var techSheet = data.techSheet;
                alert(data.status);
                if (data.status) {
                    alert("looks good");
                    $scope.Message = "";
                    $scope.showErrors = false;
                    $scope.TechSheetInfo = techSheet;
                    alert($scope.TechSheetInfo);
                    $scope.TechSheetInfoStatic = angular.copy(techSheet);
                    $rootScope.customerInfo = techSheet.Customer;
                    createpdf($scope);
                } else {
                    if (response.message !== null) {
                        $scope.Status = datae.status;
                        $scope.showErrors = true;
                        $scope.Message = data.message;
                    }
                }
            };
    
            failureFunction = function(data) {
                console.log('Error' + data);
            };
    
            TechSheetFactory.saveTechSheetAng(successFunction, failureFunction,$scope.TechSheetInfo);
        };
    /* ----------End SaveTechSheet ---------*/
    
    //------------Initialize a new tech sheet. This is the default action for the page load/refresh/discard changes/clear form
        $scope.initializeTechSheet = function() {
            $scope.TechSheetInfo = [];
            $scope.TechSheetInfoStatic = [];
            $scope.customerIDDisabled = false;
            $scope.orderIDDisabled = false;
            $rootScope.customerInfo = [];
            $scope.WindowsPassword = "";
            $scope.EmailPassword = "";
    
            const successFunction = function(response) {
                $scope.TechSheetInfo = response.data;
                $rootScope.customerInfo = response.data.Customer;
                $scope.TechSheetInfoStatic = angular.copy(response.data);
            };
    
            const failureFunction = function(response) {
                //console.log('Error' + response.status);
            };
    
            TechSheetFactory.ITS(successFunction, failureFunction);
        };
    //end initializeTechSheet
    
        $scope.getCustomerById =  function(custId) {
            const successFunction = function(response) {
                alert("success");
                $scope.TechSheetInfo.Customer = response.data;
                $scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
                $rootScope.customerInfo = response.data;
                $scope.customerIDDisabled = true;
            };
            const failureFunction = function(data) {
                alert('getcustomer fail');
                console.log('Error' + JSON.stringify(data));
            };
    
            TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
    
        };
    
    
        $scope.setOrderFromGrid = function(woInfo) {
            $scope.getCustomerById(woInfo.CustomerID);
            $scope.TechSheetInfo.WorkOrder = woInfo; //this line and the next are occurring before getCustomerById has completed
            $scope.TechSheetInfoStatic.Customer = angular.copy($scope.TechSheetInfo.Customer);
            $scope.orderIDDisabled=true;
            $scope.dvTechSheet.$setPristine();
    
        };
    
        $scope.resetForm = function() {
            if (!$scope.dvTechSheet.$pristine) {
                if (!confirm("Discard Changes?")) {
                    return;
                }
            }
            $scope.initializeTechSheet();
            $scope.dvTechSheet.$setPristine();
        };
    
    
    }]);
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Alexander    7 年前

    你失去了承诺的优势,所以你可以选择这样的承诺。(我不推荐) 从头顶上看像这样:

      // inject $q
    
      $scope.getCustomerById =  function(custId) {
        const deferred = $q.defer()
        const successFunction = function(response) {
            $scope.TechSheetInfo.Customer = response.data;
            $scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
            $rootScope.customerInfo = response.data;
            $scope.customerIDDisabled = true;
            deferred.resolve(); // can pass value if you like
        };
        const failureFunction = function(data) {
            alert('getcustomer fail');
            console.log('Error' + JSON.stringify(data));
            deferred.reject();
        };
    
        TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
       return deferred.promise;
    };
    

    /////////////

    $scope.setOrderFromGrid = function(woInfo) {
        const prom = $scope.getCustomerById(woInfo.CustomerID);
        prom.then(()=>{
           $scope.TechSheetInfo.WorkOrder = woInfo;
           $scope.TechSheetInfoStatic.Customer = 
           angular.copy($scope.TechSheetInfo.Customer);
           $scope.orderIDDisabled=true;
            $scope.dvTechSheet.$setPristine();
        })
    
    
    };