Hello everybody,
I am trying to understand the best way to load data from a server into a service. Example:
.factory( "Init", function( $http, SERVER ){
return {
get: function(){
return $http.get( SERVER.url + '/init/');
}
}
})
.controller('AppCtrl', function($scope, Init) {
Init.get().then( function(data){
console.log(data);
});
})
but in this way everytime a controller needs the data a new query is done.
Also using the service instead of the factory nothing change
.service( "Init", function( $http, SERVER ){
var promise = $http.get( SERVER.url + '/init/' )
.success(function(data){
return data;
});
return promise;
})
.controller('AppCtrl', function($scope, Init) {
Init.then( function(data){
console.log(data);
});
})
I think we have the same problem of one query for every controller, right?
Another way is to resolve from the state, like this:
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
resolve: {
myData: function (Init){
// this method is from the factory above
return Init.get();
}
},
controller: 'AppCtrl'
})
and then in the controller
.controller('AppCtrl', function($scope, myData) {
console.log(myData);
})
in this last example all other controllers that are in a child state of app will inherit myData.
But I would like to know how to set the data inside the service and not to the app state, like is now.
This is a possible solution, that works, but I don’t know if is a best practice or if I am trying to rebuild the wheel.
In the state I make the request, then use the factory method to set the object inside the service and finally resolve.
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
resolve: {
myData: function($http, Init){
return $http({ method:'GET', url: SERVER.url + '/init/'})
.then(function(data){
Init.set(data);
return data;
});
}
},
controller: 'AppCtrl'
})
.factory( "Init", function( $http, SERVER ){
var settings = {};
return {
set: function(data){
settings = data;
},
get: function(){
return settings;
}
}
});
And from the controller I can access it in this way:
.controller('OtherCtrl', function($scope, Init) {
console.log(Init.get());
})
Anyway using the resolve method we can encounter in a possible user experience issue if there’s some problem with the connection.
I feel lost!
thanks everybody for support!