Search code examples
javascriptangularjsangularjs-scope

NgIF with service is slow


I'm creating an app where some parts/elements from the application will be hidden, these parts depending of the type of user will be shown or not. One of the elements is the header section. For this I created a service where I store the user information account, and then I injected in a controller, in my case I injected in the headerController. Inside the headerController I create a variable:

vm.isProfessional = null;

Than I call the service:

 ProfileService.isType("professional").then(
                function (result) {
                    vm.isProfessional = result;

                }
            );

After in my view header.php I included:

<div  ng-if="headerCtrl.isProfessional" >
...
</div>

Is working, but the only problem is taking some time, after the page is loaded, the header element takes some time until it shows the element, and visually it isn't appealing, is there a way to make it faster, the variable vm.isProfessional receives faster the boolean value to don't take so much time? I believe what makes this taking so long time is in the service that is making a promise, but I believe that regarding this I can't do much.

Above I leave my service also. Service:

(function () {
    'use strict';

    angular
        .module('myApp')
        .factory('ProfileService', ProfileService);

    ProfileService.$inject = ['$http','UserService','$q'];

    /* @ngInject */
    function ProfileService($http, UserService,$q) {


        var service = {
            isType:            isType
        };
        return service;


        function isType(accountName) {
            var deferred = $q.defer();
            UserService.getAuthenticatedUser()
                .then(function (response) {
                    var data = response.data;
                    UserService.getUserInformation(data.user.id)
                        .then(function (response) {
                            var userDetails = response.data;
                            deferred.resolve(accountName == userDetails.account_types[0].description_internal);
                            return; 
                        });
                });

            return deferred.promise; 
        }


    }

})();

Solution

  • instead of ng-if, use ng-show or ng-hide.

    With ng-if the entire content inside your div is not processed (doesn't exist in DOM) as headerCtrl.isProfessional is false. And it will not be processed until the isType promise returns and sets headerCtrl.isProfessional to true.

    With ng-show or ng-hide, the content of the div would be processed, necessary bindings would be created. And once the service returns, it would merely flip the value of display property to visible or hidden see https://docs.angularjs.org/api/ng/directive/ngShow