S
S
Sergey2019-09-18 11:50:56
Angular
Sergey, 2019-09-18 11:50:56

How to organize a function call?

Good afternoon.
AngularJs project. There are two controllers and a factory.
the first controller calls a method from the factory to access the database.

function navbarCtrl($scope, Auth) {
    vm = this
    vm.login = async function () {
        console.log(Auth.getUsername())
        const authToken = await Auth.login(vm.credential.username, vm.credential.password)
    }
 
    vm.credential = {
        username: null,
        password: null
    }
}

If successful, the factory creates an object. The factory also has a method that returns the value of an object.
auth.getUsername = function () {
        if (auth.user && auth.user.username) {
            return auth.user.username;
        } else {
            return null
        } 
    }

The navigation menu has buttons that appear depending on the authorization status
<ul class="nav navbar-nav navbar-right" ng-controller='statusCtrl as sc' >
        <li ><a href="#/login" ng-hide='sc.getUserName()'>Sing in </a></li>
        <li ng-show='sc.getUserName()'><a href="#/login">{{sc.getUserName()}} logout</a></li>
      </ul>

they are processed by the second controller, which should change the state of the buttons.
function statusCtrl($scope, Auth) {
    vm = this
    vm.getUserName = function () {
        return Auth.getUsername()
    }
}

It calls the factory and checks for the existence of the object, but on the first click, in case of success, because the db query function is asynchronous, the getUsername value is checked, but it is still NULL, and when the object is created, there is no recheck. Is it possible to organize a getUsername function that angular will always check, even if the object in the factory that this function returns changes?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question