Why are $ stateParams available in resolution, but not DI service inside solution?
I am trying to set up a solution in a view to get some information about the user before the view is processed, because the data from the API will determine what view they see. I tried to put my service in a solution, but $stateParams
not installed when inside a service for some reason:
.state('order.sharepoint', {
url: '/sharepoint',
abstract: true,
controller: 'SharePointController',
resolve: {
OrderResolve: function(Order, $stateParams){ // Here $stateParams
return Order.fetch(); // is set correctly!
}
}
});
Ordering service
app.factory('Order', function ($q, API, $stateParams) { // HERE $stateParams
// is empty for some reason
var Order = null;
var service = {};
service.fetch = function () {
/// Here is my API call and everything
}
source to share
Here is a plunger that answers this question: Angular and UI-Router, how to set dynamic urll pattern . There we see how to work with $stateParams
and factories
.
In general, a factory is created once . This is a singleton . The decision is made as many times as it is reached. (while the created factory has already been created ... its constructor wouldn't be the best place to reuse / reset )
This will be a factory def:
.factory('GetName', ['$http', '$timeout',
function($http, $timeout) {
return {
get : function(id) {
// let get data via $http
return $http
.get("dataFromServer.json")
.then(function(response){
// simplified converter
// taking the $http result and
// by id gets the name
var converter = response.data;
var name = converter[id];
return {templateName : name};
});
},
};
}
]);
As we can see, its constructor refers to services that can be used later, often inside a method. In this case: get(id)
And this is a standard call for it inside resolver
- or even in , as in this example. templateProvider
$stateProvider
.state('parent.child', {
url: '/child/:someSwitch',
views: {
"page": {
templateProvider: function($http, $stateParams, GetName) {
// async service to get template name from DB
return GetName
.get($stateParams.someSwitch)
// now we have a name
.then(function(obj){
return $http
// let ask for a template
.get(obj.templateName)
.then(function(tpl){
// haleluja... return template
return tpl.data;
});
})
},
controller: 'viewCtrl',
}
}
});
This example should show what factory
a singleton can use IoC
to inject dependent services / factories. State related stuff that changes (i.e. NOT single) must be passed as factory
param ... Check it out here
source to share