Reputation: 780
I am doing an app with angular js, in which, in a controller, when it is loading, I try to get if the browser is geolocation capable and, if is, I try to get position. My problem is that the view loads before the position loads, so, the view is empty.
I have tried to make it with a factory, inline in the first lines of the controller, and much more. My question is, how to configure a factory to get the position and, in the controller, wait until the factory returns the position for continue loading?
My factory:
.factory('geoLocator', function($http, $q){
var getPosition = function(){
navigator.geolocation.getCurrentPosition(function(posicion){
respuesta = {status: "ok", latitud: posicion.coords.latitude, longitud: posicion.coords.longitude};
}, function(objPositionError){
var respuesta = {status: "error", message: ""};
switch (objPositionError.code)
{
case objPositionError.PERMISSION_DENIED:
error.message = "No se ha permitido el acceso a la posición del usuario.";
break;
case objPositionError.POSITION_UNAVAILABLE:
error.message = "No se ha permitido el acceso a la posición del usuario.";
break;
case objPositionError.TIMEOUT:
error.message = "El servicio ha tardado demasiado tiempo en responder.";
break;
default:
error.message = "Error desconocido.";
}
return respuesta;
}, {
enableHighAccuracy: true,
maximumAge: 75000,
timeout: 50000
});
console.log("Respuesta: "+JSON.stringify(respuesta));
return respuesta;
};
var getIfActive = function(){
var active = false;
if(navigator.geolocation){
active = true;
}else{
active = false;
}
return active;
}
return {
getActive: getIfActive,
getCurrentPosition: getPosition
}
});
I have tried with promises too, with same result.
Controller:
.controller('AyudarCtrl', function($scope, $rootScope, $ionicLoading, $http, geoLocator) {
$scope.geoAccepted = geoLocator.getActive();
$scope.geoPosition = geoLocator.getCurrentPosition();
console.log($scope.geoPosition);
});
EDIT:
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/')
$stateProvider.state('home', {
url: '/',
templateUrl: 'home.html'
})
.state('ayudar', {
url: '/ayudar',
templateUrl: 'ayudar.html',
controller: 'AyudarCtrl'
})
.state('recibir', {
url: '/recibir',
templateUrl: 'recibir.html',
controller: 'RecibirCtrl'
})
.state('agradecimientos', {
url: '/agradecimientos',
templateUrl: 'agradecimientos.html',
controller: 'AgradecimientosCtrl'
})
})
Upvotes: 0
Views: 149
Reputation: 28750
Is your controller behind a route?
If so you can use the resolve property when building routes with the factory you've created along with promises to prevent the route from loading until your factory is finished.
If the controller is not behind a route, you'll have to wrap all your logic after your service has been executed in the controller.
Upvotes: 1