$ http在AngularJS中被多次调用 [英] $http is getting called multiple times in AngularJS

查看:45
本文介绍了$ http在AngularJS中被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,每次都多次调用$ http调用.检查下面的代码.

In my project the $http call is getting called more than once every time. Check the code below.

router.js

angular.module('adminsuite',['ngFileUpload','ui.router','ngCookies','angular-clipboard','ngAnimate', 'ngSanitize', 'ui.bootstrap','ngMessages']).constant("__env",env).config(function($stateProvider, $urlRouterProvider, $locationProvider) {

$urlRouterProvider.otherwise('/');
//$locationProvider.html5Mode(true);
$stateProvider
    .state('login', {
        url: '/',
        views:{
            header:{
                templateUrl: '',
                controller: ''
            },
            pageContent:{
                templateUrl: 'Login/login3.html',
                controller: 'loginController'
            },
            footer:{
                templateUrl: 'common/footer3.html',
                controller: 'footerController'
            }
        }



    })

    // HOME STATES AND NESTED VIEWS ========================================
    .state('dashboard', {
        url: '/dashboard',
        views:{
            header:{
                templateUrl: 'common/header.html',
                controller: 'headerController'
            },
            pageContent:{
                templateUrl: 'dashboard/dashboard.html',
                  controller: 'dashboardController'
            },
            footer:{
                templateUrl: 'common/innerFooter.html',
                controller: 'footerController'
            }
        }
    })
    //SURVEY STATES
    .state('survey', {
        url: '/survey',
        views:{
            header:{
                templateUrl: 'common/headerTool.html',
                controller: 'headerController'
            },
            pageContent:{
                templateUrl: 'survey/survey.html',
                  controller: 'surveyController'
            },
            footer:{
                templateUrl: 'common/innerFooter.html',
                controller: ''
            }
        }
    }).state('survey.surveyList', {
        url: '/:id',
        templateUrl: 'survey/surveyList.html',
        controller: ''
    }).state('survey.surveyList.details', {
        url: '',
        templateUrl: 'survey/survey-details/summary.html',
        controller: ''
    }).state('survey.surveyList.questionare', {
        url: '',
        templateUrl: 'survey/questionare/questionare.html',
        controller: 'questionareController'
    }).state('survey.surveyList.sampleManagement', {
        url: '',
        templateUrl: 'survey/sample-management/sample-management.html',
        controller: ''
    }).state('survey.surveyList.quotaManagement', {
        url: '',
        templateUrl: 'survey/quota-management/quota-management.html',
        controller: 'quotaController'
    }).state('survey.surveyList.scheduling', {
        url: '',
        templateUrl: 'survey/scheduling/scheduling.html',
        controller: ''
    }).state('survey.surveyList.notification', {
        url: '',
        templateUrl: 'survey/notification/notification.html',
        controller: ''
    }).state('survey.surveyList.reports', {
        url: '',
        templateUrl: 'survey/reports/reports.html',
        controller: ''
    }).state('survey.surveyList.location', {
        url: '',
        templateUrl: 'survey/location/location.html',
        controller: ''
    });

    // ABOUT PAGE AND MULTIPLE NAMED VIEWS =================================

 })

loginAuthentication.js

UserService.GetByUsername(requestData)
                .then(function (user) {
                    console.log(user);
                    if (user.SessionID) {
                       sessionID = user.SessionID;
                       userDetails = user.UserProfile;
                       response = { success: true};
                    } else {
                        response = { success: false, message: 'Username or password is incorrect' };
                    }
                    callback(response);
                });

UserService.js

function GetByUsername(user) {
        //console.log(__env.apiUrl);
        return $http.post(__env.apiUrl+'/UserAuthentication/login',  user, {headers: { 'Content-Type': 'application/json'}}).then(handleSuccess, handleError('Error getting user by username'));
    }

当我在后端调用此函数时,它被多次调用.其他API也发生了同样的事情.

When I call this function in the backend it is called more than once. And the same thing is happening for the other APIs.

我删除了所有重复的控制器,但是问题仍然存在.

I removed all the duplicate controllers, but the issue persists.

一个特别的问题是在$ http调用的标头部分中发送令牌ID,但是后端的此调用发生了两次,甚至更多.第一次,此标头令牌显示为空,第二次或更多次显示结果.请检查以下代码.

One particular issue what am getting is sending the token id in the header section of $http call, but this call in back end happening two times and some times more than that. In first time this header token shows empty and second times or more than that time it is giving the result. please check the below code.

api调用

$http.get(__env.apiUrl+'/UserSurvey/GetAllSurveys',  {
                            headers: { 'Content-Type': 'application/json','SessionID':$rootScope.token}
                                })
                .then(function(response){
                        console.log(response);
                            return response.data;
                        }, function(error){
                             console.log("error");
                              console.log(error);
                            return error;
                        });

推荐答案

您可能遇到了摘要循环问题.

当我的AJAX模块位于纯Javascript中时,我的数据将在第一个服务器查询上呈现.但是,当我将AJAX模块放在AngularJS模块中时,必须在数据渲染之前两次查询服务器.请注意,查询是从用户界面调用的.

You might be having a digest cycle issue.

When my AJAX module is located in plain Javascript my data renders on the first server query. However, when I place my AJAX module in an AngularJS module I must query the server twice before my data renders. Note the query is invoked from the UI.

经过一番摸索,我意识到数据确实到达了第一个查询,并且已分配给所有指定的对象和变量,但仅在AngularJS代码的范围内.当然,数据是异步到达的,并且UI已经经历了摘要周期,并且没有理由再去,因为UI中的任何内容都没有改变.当UI发生更改时,Angular会更新所有内容,但更改(到达数据)来自服务器时将不执行任何操作.

After poking around I realized the data had indeed arrived on the first query and was assigned to all designated objects and variables but only within the scope of the AngularJS code. Of course, the data had arrived asynchronously and the UI had already gone through a digest cycle and had no reason to go again because nothing in the UI had changed. When there’s a change in the UI Angular updates everything but does nothing when the change (arriving data) comes from the server.

随后,第二个相同的查询将强制执行摘要循环,并使用第一个查询中已经存在的数据更新所有绑定.因此,目标是从Javascript强制进行摘要循环以更新您的UI绑定.现在,我在回调函数的末尾强制执行摘要循环.要强制执行摘要循环,请在数据变量分配完成后将Angular方法 $ scope.$ apply([exp])放置.我在以下Angular文档中找到了有用的详细信息: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply ,并在以下示例中提供了很好的解释,并提供了工作示例:如何调用$ scope.$ apply()使用"controller as"语法,希望它可以解决双重HTTP调用的问题.

Subsequently, the second identical query would force a digest cycle and update all the bindings with the data that was already sitting there from the first query. Thus the objective is to force a digest cycle from Javascript to update your UI bindings. I now force a digest cycle at the end of my callback function. To force a digest cycle place the Angular method $scope.$apply([exp]) after your data variable assignments are complete. I found helpful details in the Angular docs at: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply and also a great explanation with working examples at: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html and an important detail about using the "controller as" syntax when forcing a digest cycle at: How to call $scope.$apply() using "controller as" syntax and hopefully this fixes the problem of the double HTTP call.

这篇关于$ http在AngularJS中被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆