B
B
Bogopodoben2016-07-26 14:53:45
Angular
Bogopodoben, 2016-07-26 14:53:45

How to make a function execute synchronously in angularjs?

How to make a function execute synchronously?
I tried a bunch of ways, including promice, nothing comes out, the execution of the function happens asynchronously.
In this case, we pass the role to the function, for which we need to request data from the api and display true or false in RUN config.

authService.checkApiRoles = function (authorizedRoles) {
    console.log('1');

    if (authorizedRoles == 'user') {
      var resultRole;
      $http.get('URL')
      .then(function(res){
        resultRole = res.data.result;
        console.log(resultRole);
        console.log('2');
      })
    };

    console.log('3');
    return resultRole;
  };

In this case, the function is executedbd69e5e698c243f2b16fc2ed372e844f.PNG

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2016-07-26
@Bogopodoben

And you want synchronous requests to the server? Why the hell? It should be like this:

authService.checkApiRoles = function (authorizedRoles) {
  var promise = $http({
      url: "URL",
      method: 'GET',
      headers: {}
    })
    .then(function (response) {
      var resultRole = response.data.result;
      return resultRole;
    });
  return promise;
}

**********************************************
Example of using resolve router
/**
 * Роут "Личный кабинет""
 */
$stateProvider
    .state({
        name: 'user', 
        url: "/user",
        templateUrl: "routes/user/user.html",
        controller: 'userController as User',
        resolve: {
            authState: function (userFactory) {
                return userFactory.ValidSession()
                    .then(function (result) {
                        return result;
                    });
            }
        }
    })

// метод сервиса проверяющий валидность сессии на сервере
function ValidSession() {
    var promise = $http({
            url: API.makeUrl(API.URLS.user, "valid"),
            method: 'GET',
            params: {},
            headers: {}
        })
        .then(function (response) {
            $log.debug("ValidSession success: ", response.data);
            var response_data = angular.fromJson(response.data);
            return response_data.valid;
        });
    return promise;
}

// authState инжектится в контроллер
if (authState === true) {
    $state.go('user.profile');
} else {
    $state.go('login');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question