Dpk_Gopi
Dpk_Gopi

Reputation: 267

Http calls are happening twice in angular.js

Possible Duplicate of $http is getting called multiple times in AngularJS

Sorry I didn't have 50 reputations to comment on the same post. We are calling the API's using http service and all the services have session id that been passed through cookiestore value. The API call doesn't work for first time as session id is null during first call and it works only for the second call.

Can anyone help us with this. We have multiple API's and all are happening twice which is actually increasing the load. And yes we have researched it.

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: ''
            }
        }
    });

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

 })

LoginAuthenticationService.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.js

 $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;
                        });

Any help appreciated.

Upvotes: 2

Views: 3315

Answers (2)

J0rdAn
J0rdAn

Reputation: 151

Assuming, you have declared controllers within your application using AngularUI state definitions such as the following:

$stateProvider
 .state('index',
 {
   url          :   '/',
   templateUrl  :   'templates/home.html',
   controller   :   'HomeController'
 })

And then, in the home.html view template, you also declare the controller using the ng-controller directive like so:

<div ng-controller="HomeController">

Then you have, without realising it, attached the controller twice (once through the state definition and twice through the ng-controller directive) which causes the code contained within the controller to execute twice as well.

Upvotes: 2

user5224681
user5224681

Reputation: 41

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.

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.

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.

Upvotes: 1

Related Questions