0

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.

4
  • What is your problem with this approach? Commented Jul 13, 2016 at 7:19
  • as per my knowledge, We need to inject any service before using it in any controller, similary I was thinking I need to inject the constant before using it into the factory method, so I tried to inject it using CustomerService.$inject = ['BaseApiURL']; But then the code stopped working. I was looking for the explanation. Commented Jul 13, 2016 at 7:22
  • What error did you get..? Commented Jul 13, 2016 at 7:32
  • 1
    Did u just call CustomerService.$inject = ['BaseApiURL'];? May be in your case it should be CustomerService.$inject = ['BaseApiURL','$resource'];. Commented Jul 13, 2016 at 7:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.