I need to use $http
service in config method. But I can't use $http
in config, I am getting unknown Provider
error message.
My code :
.config(function($http, $routeProvider, $provide) {
$http.get("sampleslist.js").success(function(data) {
var loop = 0, currentRoute;
for (loop = 0; loop < data[loop].pages.length; loop++) {
currentRoute = data[loop].pages;
var routeName = "/" + currentRoute[loop].name;
$routeProvider.when(routeName, {
templateUrl:"/" + currentRoute.name + ".html",
})
}
})
app = {controller: $controllerProvider.register}
})
Can you please provide the solution for this?
It's not a good practice to use $http
in the .config
. One can use it either in .run
or can make use of the service using either .service
or .factory
.
If just need to make AJAX request you can actually retrieve $http server from the new injector:
.config(function($routeProvider, $provide) {
var $http = angular.injector(['ng']).get('$http');
$http.get("sampleslist.js").success(
function(data) {
var loop = 0,
currentRoute;
for (loop = 0; loop < data[loop].pages.length; loop++) {
currentRoute = data[loop].pages;
var routeName = "/" + currentRoute[loop].name;
$routeProvider.when(routeName, {
templateUrl: "/" + currentRoute.name + ".html",
})
}
})
app = {
controller: $controllerProvider.register,
}
})
We cannot use http in config. For more details please check this link:
You can inject only providers in .config file. but $http is not provider, your angular app is searching for provider named $http but it is not able to find it so it threw error.
How to resolve this??
If you want any ajax call before your angular controller loading you can do it in .run
Do you have control over sampleslist.js
? If yes, maybe just download it using tag and assign values to variables.
//sampleslist.js
var samplelist = {...}
//index.html
<script src="samplelist.js"></script>
Then you could inject this values to angular using angular.constant
or just use variable samplelist
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.