I am making a web page with ui-router
. Before we enter the controller, I want some operations to be done: 1) create a temporary folder in the server and write some files; 2) record the name of the folder and some other data. So naturally I choose to use resolve
.
.state('panels', {
controller: 'PanelsCtrl',
resolve: {
init: ['codeService', function (codeService) {
return codeService.init()
}]
},
...
});
app.service('codeService', ['$http', function ($http) {
var srcP = "default" // private variable
this.getSrcP = function () { return srcP };
this.init = function () {
return $http.post("/writeFiles", ...) // write files in a temporary folder of the server
.then(function (res) {
srcP = res.data;
return srcP
}
}
};
app.controller('PanelsCtrl', ['$scope', 'codeService', 'init', function($scope, codeService, init) {
$scope.src = codeService.getSrcP();
...
}
The above code works. However, I feel odd about 1) I resolve an asynchronous function (ie, init
) rather than data (that people usually resolve); 2) I use a side effect of init
to record data (ie, srcP
) in a service.
It seems that, in comparaison with resolving data, it is easier when we have more data to be recorded, we just need to have more private variables and make more side effects in the service.
Does anyone know if what I do is a bad/common/good practice? Additionally, why codeService
in resolve: {...}
and codeService
injected to PanelsCtrl
share same private variables?