Answer the question
In order to leave comments, you need to log in
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;
};
Answer the question
In order to leave comments, you need to log in
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;
}
/**
* Роут "Личный кабинет""
*/
$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 questionAsk a Question
731 491 924 answers to any question