无法使用Laravel框架在Angular中进行异步HTTP调用

时间:2017-04-26 02:15:08

标签: javascript angularjs asynchronous http-headers

我面临一个非常奇怪的问题,即我能够在我的本地Cent-OS环境中进行异步HTTP调用,但只要我将代码推送到演示服务器,就会以某种方式执行HTTP调用异步。

以下是我尝试执行的功能

$scope.getResults = function(){

$http({
    url: /getResults, 
    method: 'POST', 
    data: data,
    headers: {'async': true}
})
.then(function (response) {

    var contactId = response.data.contactId[0];
    $scope.loadProfileInfo(contactId);

    var requestId = response.data.requestId;
    $scope.getTotalCount(requestId);


}

});

};

$scope.loadProfileInfo = function(id){

$http({
    url: /getProfileInfo, 
    method: 'POST', 
    data: {contactId: id},
    headers: {'async': true})
.then(function (response) {
    //perform operations
});

};

$scope.getTotalCount = function(id){

$http({
    url: /getTotalCount, 
    method: 'POST', 
    data: {some: data},
    headers: {'async': true})
.then(function (response) {
    //perform operations
});

};

当我调用函数getResults()时,它会加载结果并调用函数loadProfileInfo(),它会按预期加载配置文件信息。 现在的问题是函数getTotalCount需要花费更长的时间来执行,直到它不返回响应,即使它们非常小,也不会处理其他HTTP调用。

我正在使用Laravel PHP框架。

真实代码 参考:

pageChangeHandler() = getResults()
getCount() = getTotalCount()
showProfileAction() = loadProfileInfo()


$scope.pageChangeHandler = function(num) {

        $scope.checkMoreResults = false;

        console.log("pageChangeHandler begins");
        //removing cached values from previous results
        $("#analyticsResults").text("...");
        $scope.showTitleLevelGraph(['','','','',''], [0,0,0,0,0]);
        $scope.showScoreGraph([0,0,0,0,0,0]);
        $scope.showGenderGraph([0,0,0]);
        $scope.showCompanySizeGraph([0,0,0,0]);

        $scope.analyticsFlag = false;
        $("#loading-bar").show();
        $("#loading-spinner").show();
        if ($window.Math.ceil(num*50)>50000){
            sweetAlert("Oops", "Seeking is limited to 50,000 results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
        } else {
            $('body').css('cursor', 'progress');

            // if downloadList exists, save it so it can be added to after reloading.

            if ($scope.downloadList.length>0) {
                $scope.storedSelectedContacts = angular.copy($scope.downloadList);
                $scope.storedLiUrl = angular.copy($scope.liUrl);
                $scope.storedCompanyName = angular.copy($scope.companyName);
                $scope.storedCompLink = angular.copy($scope.compLink);
            }

            $scope.selectedPage = num;
            //$scope.showProfile = false;
            //$scope.profileData = null;

            if (num > 1 || null!==$scope.shortCode) {
                // use code
                var data = {'code': $scope.shortCode};
            } else {
                $scope.shortCode = null;
                var data = angular.copy($scope.wizardData);
                console.debug(data+" "+JSON.stringify(data));
                try{
                    if (data.state.length > 0) {
                        for (var x = 0; x < data.state.length; x++) {
                            data.tbl_company_State[x] = data.state[x].value;
                        }
                        data.state = null; // null it out to prevent issues in LV controller
                    }
                }catch(e){
                }

            }
            //console.debug(data);

            if ($scope.searchFast == true){
                var url = $scope.baseUrl + "/search/fast?page=" + num;
            } else {
                var url = $scope.baseUrl + "/search/wizard?page=" + num;
                console.log("wizard: "+num);
                var newsearch = true;
            }
            console.log("Real data: "+JSON.stringify(data));

            $http({
url: url, 
  method: 'POST', 
  data: data,
  headers: {'async': true}
})
                .success(function (response) {
                    (function() {
                        setTimeout(function() {
                            // code-here

                    //response = response.data;
                    console.log("Search results: "+JSON.stringify(response));
                    $('body').css('cursor', 'auto');
                    //console.debug(response);
                    if (response.error){
                        if (response.error == 1000000) {
                            sweetAlert("Oops", "Your search returned more than 1 million results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
                            $scope.totalResults = '1000000+';
                        } else {
                            sweetAlert("Oops", response.error, "error");
                            $scope.totalResults = '0';
                        }

                    } else {
                        if (response.data) {
                            //loading the profile of the first result from the fast load
                            $scope.selectedAll = false;
                            $scope.searchResults = response.data;                            
                            $scope.totalResults = response.total;
                            $scope.resultStart = $window.Math.ceil((response.per_page * response.current_page) - response.per_page + 1);
                            $scope.resultEnd = $window.Math.ceil(response.per_page * response.current_page);
                            if ($scope.resultEnd > $scope.totalResults) {
                                $scope.resultEnd = angular.copy($scope.totalResults);
                            }
                            $scope.resultsPerPage = response.per_page;
                            $scope.pageSize = $scope.resultsPerPage;
                            $scope.lastPage = response.last_page;
                            $scope.currentPage = response.current_page;
                            if (response.code) {
                                $scope.shortCode = response.code;
                                $scope.disableRange = false;
                            }

                            $scope.shareUrl = $scope.baseUrl + '/search/code/' + $scope.shortCode;
                            console.log();
                            if (response.data.length > 0) {
                                if ($scope.currentPage > 1 && $scope.passedCode!='') {
                                    $scope.passedCode=''
                                }
                                if ($scope.currentPage == 1 && ($scope.searchFast==true || $scope.searchFast==null)) {
                                    //------Edit Jeet kapadia---// 
                                    if($scope.newSearchFlag == false){
                                        $scope.showResults = true;
                                        //loading the profile of the first result from the fast load
                                        $scope.firstContactId = response.data[0].ContactID;
                                        console.log("1 Profile loaded");
                                        $scope.showProfileAction($scope.firstContactId);
                                    }

                                    }*/


                                    //-----End Jeet Kapadia-----//
                                }
                                    if(newsearch == true && $scope.newSearchFlag == true){
                                        //console.log(response.data[0]);
                                            //$scope.newSaveSelectSearch();   
                                            $scope.showResults = false;
                                            newsearch = "false"; 
                                    }

                                angular.forEach($scope.searchResults, function (item) {
                                    item.Selected = false;
                                    if (arrayObjectIndexOf($scope.storedSelectedContacts, item.ContactID)>-1 || arrayObjectIndexOf($scope.downloadList, item.ContactID)>-1) {
                                        item.Selected = true;
                                    }
                                });
                                $scope.buildDownloadList();
                                if (response.more){
                                    $scope.totalResults = 'Loading...';
                                    $scope.searchFast=false;
                                    $scope.disableRange = true;
                                    $scope.checkMoreResults = true;
                                    $scope.pageChangeHandler(1); 
                                }else{
                                    $scope.getCount();

                                    //reloading the profile of the first result if the contact changes after all
                                    //the records have been loaded
                                    if($scope.firstContactId != response.data[0].ContactID){
                                        console.log("2 Profile loaded: "+$scope.firstContactId+" "+response.data[0].ContactID);
                                        $scope.showProfileAction(response.data[0].ContactID);
                                    }
                                    //fetching all results to perform analytics on
                                    console.log("short code: "+$scope.shortCode);
                                    //globalAnalyticsInterval = $interval(function () {



                                }

                            } else {
                                sweetAlert("Oops", "Your search returned 0 results. Please widen your search parameters a bit.", "error");
                            }
                        }
                    }
                    }, 500)
                    })()
                });
        }
    };

    $scope.getCount = function(){

        var data = angular.copy($scope.wizardData);
        console.debug(data+" "+JSON.stringify(data));
        try{
            if (data.state.length > 0) {
                for (var x = 0; x < data.state.length; x++) {
                    data.tbl_company_State[x] = data.state[x].value;
                }
                data.state = null; // null it out to prevent issues in LV controller
            }
        }catch(e){
        }
        var url = $scope.baseUrl + "/search/getCount";
        $http.post(url, data)
            .success(function (response) {

                //response = response.data;

                $scope.lastPage = response.last_page;
                $scope.totalResults = response.total;
                console.log("Count: "+JSON.stringify(response));

        });

    };

$scope.showProfileAction = function(id) {
        $scope.liTimeoutFlag = false;
        $scope.liResponseFlag = false;
        $scope.storedContactId = id;
        console.log("showProfileAction: "+id);
        $scope.showProfile = false;
        $scope.profileData = null;
        $("#qualityScoreText").text("Verifying");
        $scope.socialScoreFlag = false;
        $scope.emailScoreFlag = false;
        $("#profileInfo").addClass("visibilityHidden");
        try{
            $scope.canceller.resolve();
        }catch(err){
            //console.log("showProfileAction: "+err.message);
        }
        $scope.userNoteContactId = id;

        //getting user notes for the contact
        $scope.getUserNoteComment(id);

        //console.debug(id);
        if (id > 0) {
            $scope.idContactSelected = id;
            var url = $scope.baseUrl + "/search/contact/" + id;

            $('body').css('cursor', 'progress');
            $('#profilePanel').css('background-color: #ccc');
            $http.get(url)
                .then(function (response) {
                    response = response.data;
                    $('body').css('cursor', 'auto');
                    $('#profilePanel').css('background-color: #fff');
                    if (response.error) {
                        sweetAlert("Oops", "Contact info could not be loaded.", "error");
                    } else {
                        if (response.id) {
                            if ($scope.mapMarker!==null) {
                                $scope.mapMarker.setMap(null);
                            }
                            $timeout(function(){
                                $scope.showProfile = true;
                            }, 100)
                            $scope.profileData = response;
                            $("#profileInfo").removeClass("visibilityHidden");
                            $scope.lat = parseFloat($scope.profileData.Latitude).toFixed(6);
                            $scope.lon = parseFloat($scope.profileData.Longitude).toFixed(6);
                            $scope.mapOptions = {
                                zoom: 14,
                                center: new google.maps.LatLng($scope.lat, $scope.lon),
                                // Style for Google Maps
                                styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
                                mapTypeId: google.maps.MapTypeId.ROADMAP
                            };
                            $scope.mapMarker = new google.maps.Marker({
                                map: $scope.myMap,
                                position: $scope.mapOptions.center
                            });

                            for(var key in $scope.profileData) {
                                //console.log(key+" "+$scope.profileData[key]); 
                            } 

                            //verifying the email address of the loaded profile
                            var emailUrl = $location.protocol() + '://'+ $location.host() + '/contact/verify/' + id;
                            $http.post(emailUrl)
                                .then(function (result) {

                                    var singleVerificationKey = result.data.verification_key; 
                                    var emailStatus = result.data.status;
                                    var singleEmailResult = result.data.result;
                                    console.log("single email call: "+JSON.stringify(result)+" "+emailStatus);
                                    if($scope.storedContactId == result.data.contactid){
                                        if(emailStatus == "0"){ //when something goes wrong while verifying the email
                                            $("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
                                        }else if(emailStatus == "2"){ //when the email is verified in last 24 hours
                                            if((singleEmailResult == 'pass')){ //success
                                                $("#qualityScoreEmail").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact IS up to date.'></i> Email");
                                            }else if((singleEmailResult == 'fail')){ //failed
                                                $("#qualityScoreEmail").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is NOT up to date.'></i> Email");
                                            }else if((singleEmailResult == 'unknown')){ // unknown
                                                $("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
                                            }
                                        }else if(emailStatus == "1"){
                                            console.log("single email key: "+singleVerificationKey);
                                            //instantiate a Pusher object with our Credential's key
                                            var pusher = new Pusher('2703a05dc7f552e2a2d5', {
                                                encrypted: true
                                            });

                                            //Subscribe to the channel we specified in our Laravel Event
                                            var channel = pusher.subscribe(singleVerificationKey);

                                            //Bind a function to a Event (the full Laravel class)
                                            channel.bind('EmailSingleVerification', $scope.singleEmailVerification);
                                        }
                                    }else{
                                        console.log("single email creation information from previous request");
                                    }

                            });

                            // //verifying the social information of the loaded profile
                            var liUrl = $scope.baseUrl + '/socialVerifyBatch';
                            var contactIdArr = [id];
                            var postData = {'id': contactIdArr, 'background': false};
                            $http.post(liUrl, postData)
                            .then(function (result) {

                                setTimeout(function () {
                                    console.log("Timeout: start");
                                    $scope.liTimeoutFlag = true;
                                    if(($scope.storedContactId == result.data.contactid) && (!$scope.liResponseFlag)){
                                        console.log("Timeout: making unknown");
                                        $("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
                                        $scope.animateScore($scope.profileData.Quality_Score, $scope.profileData.Quality_Score-1, 1000);
                                        console.log("here 1");
                                        var url = $scope.baseUrl + '/contact/verifySocial/' + $scope.storedContactId + "/6";
                                        $http.post(url)
                                            .then(function (result) {
                                                console.log("Timeout: Update quality score: "+JSON.stringify(result));
                                            }
                                        );
                                    }
                                }, 20000);

                                console.log("single li: "+JSON.stringify(result)+" "+$scope.storedContactId+" "+result.data.contactid);
                                if($scope.storedContactId == result.data.contactid){
                                    //if the social information was verified in last 24 hours
                                    if(result.data.status == "exist"){
                                        if(result.data.passed == 1){ //success
                                            $("#qualityScoreSocial").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact IS up to date.'></i> Social");
                                        }else if(result.data.failed == 1){ //failed
                                            $("#qualityScoreSocial").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is NOT up to date.'></i> Social");
                                        }else if(result.data.unknown == 1){ // unknown
                                            $("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
                                        }
                                    }else if(result.data.status == "done"){
                                        var uniqueString = result.data.download_key;
                                        console.log("karthik key: "+uniqueString);

                                        //instantiate a Pusher object with our Credential's key
                                        var pusher = new Pusher('2703a05dc7f552e2a2d5', {
                                            encrypted: true
                                        });

                                        //Subscribe to the channel we specified in our Laravel Event
                                        var channel = pusher.subscribe(uniqueString);

                                        //Bind a function to a Event (the full Laravel class)
                                        channel.bind('SocialBulkVerification', $scope.singleSocialVerification);
                                        console.log("end karthik key");

                                    }
                                }else{
                                    console.log("single social creation information from previous request");
                                }
                            });

                        }
                    }


                });
        } else {
        }
    }

感谢任何帮助。提前谢谢。

0 个答案:

没有答案