Badhon Jain
Badhon Jain

Reputation: 1007

How can we inject dependency into angular factory using $inject?

I'm trying to define a constant and inject that into a factory. My Constant is defined as follows:

angular.module("ContactApp").constant("BaseApiURL", "http://localhost:31523/api/");

My factory is defined as:

angular.module("ContactApp").factory('CustomerService', CustomerService);

//CustomerService.$inject = ['BaseApiURL']; Giving Error when this line is active.

function CustomerService(BaseApiURL, $resource) {

    return $resource(BaseApiURL + 'Customers');
};

The above code is working, but don't I need to inject the constant as dependency into the factory method? I can inject the constant using the $inject into a controller but couldn't do that into the factory.

Upvotes: 0

Views: 51

Answers (1)

MMhunter
MMhunter

Reputation: 1441

In angular's dependency injection, if you don't do dependency annotation (like setting .$inject), angular will assume that the function parameter names are the names of the dependencies.

But don't rely on this feature since it will cause problem when you attempt to minify your code.

So the best practice should be do dependency annotation wherever there is dependency injection.

Btw u can set $inject in factory but maybe u should call CustomerService.$inject = ['BaseApiURL','$resource']; in your case.

Upvotes: 1

Related Questions