Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can $q and $http be injected in the .config section

Tags:

angularjs

Is it possible to inject $q in the config section of my module? Below is my sample config section.

.config(['$q', function ($q) {
    var func = function (inp) {
        var def = $q.defer();

        if (inp == 1)
            def.resolve("Success");
        else
            def.reject("Failure");

        return def.promise;
    };

    alert(func(1));
}]);

The first error i am getting is Uncaught Error: Unknown provider: $q from ReportModule If i change

.config(['$q', function ($q) {}])

to

.config(['$qProvider', function ($q) {}])

then i get a error saying Uncaught TypeError: Object # has no method 'defer' from ReportModule

Seems like i cant inject $q in config section. Is that the case or am i doing something wrong? I have a usecase where i need to use $q and $http in the config section of my module for initialization. Is there some technique for doing this?

like image 622
Sarvesh Avatar asked Dec 17 '13 05:12

Sarvesh


People also ask

Which components can not be injected as a dependency in AngularJS?

Note that you cannot inject "providers" into run blocks. The config method accepts a function, which can be injected with "providers" and "constants" as dependencies. Note that you cannot inject "services" or "values" into configuration.

Which components can be injected as dependency in AngularJS?

26) Which of the following components can be injected as a dependency in AngularJS? Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.

Which components can not be injected as a dependency in AngularJS application module constant value Factory?

You cannot inject values into the module. config() function. Instead constants are used to pass values at config phase.

Why is $q service used?

$q is an angular defined service. It's the same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply. resolve(value) – resolves the derived promise with the value.


2 Answers

Correct--you can't inject $http or $q from a config function. They are not available yet (they're also being configured!).

like image 107
Jeff Hubbard Avatar answered Oct 05 '22 09:10

Jeff Hubbard


You can use angular.injectorto load $http and $q, and probably other services in your config block:

angular.module('myApp').config(function () {
    var injector = angular.injector(['ng']),
        http = injector.get('$http'),
        q = injector.get('$q');
});
like image 31
Alex Ross Avatar answered Oct 05 '22 09:10

Alex Ross