2

When I trying call function from another file I get error:

TypeError: Cannot read property 'getCurrentUserFullName' of undefined

in app.js:

    'use strict';

    var testApp = {};

    var App = angular.module('testApp', ['testApp.filters', 'testApp.services', 'testApp.directives',
            'ngRoute']);

    App.run(['$location', '$rootScope', function ($location, $rootScope) {

        $rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils) {
           if(!$rootScope.userFullName){
                var userFullName = AuthUtils.getCurrentUserFullName();
                if(userFullName) {
                    $rootScope.userFullName = userFullName;
                    $rootScope.authenticate = true;
                } else {
                    $rootScope.authenticate = false;
                    $rootScope.userFullName = "";
                }
            }
        });

    }]);

AuthUtils.js

    'use strict';

    angular.module('testApp')
        .factory('AuthUtils', function AuthUtils($rootScope, $http) {
            return {
                getCurrentUserFullName: function () {
                    $http.get('auth/userFullName').success(function (user) {
                        return user;
                    }).error(function (data, status) {
                        return "error";
                        console.error(status, data);
                    });
                }
            };
        });

Why doesn't work?

1 Answer 1

3

You missed to inject AuthUtils inside run block. Inject it so factory instance would be available in run block

App.run(['$location', '$rootScope', 'AuthUtils', //<== injected AuthUtils here
    function ($location, $rootScope, AuthUtils) { //<== and here

Additonally you need to remove AuthUtils parameter from $routeChangeSuccess function, which was killing existence of injected AuthUtils in run block.

Change to

$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) //<--removed AuthUtils

From

$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, but now I've an error "Uncaught Error: [$injector:unpr] errors.angularjs.org/1.5.0/$injector/…"
Thank you, I did as above and I changed order import js files and works!
@Pablo glad to know that.. do upvote & accept answer..if it does helped you.. Thanks :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.