Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown $http Provider in Angular

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?

like image 457
Gokul Kumar Avatar asked Aug 16 '16 07:08

Gokul Kumar


4 Answers

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,
    }
})
like image 22
dfsq Avatar answered Oct 12 '22 12:10

dfsq


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

like image 40
Akash Bhandwalkar Avatar answered Oct 12 '22 10:10

Akash Bhandwalkar


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.

like image 195
Shashank Avatar answered Oct 12 '22 11:10

Shashank


We cannot use http in config. For more details please check this link:

use $http inside custom provider in app config, angular.js

like image 37
Mohan P Avatar answered Oct 12 '22 12:10

Mohan P