How can I initialize my angularjs app contant with reponse of a GET request.
For example :-
angular.module('A',[]);
angular.module('A').run( function ($rootScope,$http){
$rootScope.safeApply = function (fn) {
$http.get('url').success(function(result){
// This doesn't work. I am not able to inject 'theConstant' elsewhere in my application
angular.module('A').constant('theConstant', result);
});
var phase = $rootScope.$$phase;
if (phase === '$apply' || phase === '$digest') {
if (fn && (typeof (fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
});
I want to set the constant while my app get initialized and be able to share the constant across my components.
What's is the best approach to accomplish this?
As explained in this blog post, you can init a constant before bootstrapping your app:
(function() {
var app = angular.module("A", []);
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
return $http.get("/path/to/data.json")
.then(function(response) {
app.constant("myData", response.data);
})
.then(function bootstrapApplication() {
angular.element(document).ready(function() {
angular.bootstrap(document, ["A"]);
});
});
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With