Private angular service or controller

I have an angular module that contains some 'private' services. These private services are needed only by other services in one module, and it makes sense to test them. But I do not want other modules to use these services.

Is it possible to mark such services as 'private'? Is there at least an agreement to name these services so that others recognize them as closed?

+6
source share
1 answer

If the only reason you need these "classes", which should be angular Services, is to painlessly inject your dependencies, you can use $injector.instantiate to create them without registering as services.

Code example:

 var PrivateClass = (function () { function PrivateClass($log) { this.hello = function () { $log.debug("Hello World!");} } PrivateClass.$inject = ["$log"]; return PrivateClass; })(); angular.module('TestApp', []).run(['$injector', function ($injector) { var p = $injector.instantiate(PrivateClass); p.hello(); }]); 

You would use $injector.instantiate(PrivateClass) in the constructor (or anywhere) in the services it needs to create an instance of PrivateClass. If you want PrivateClass to behave as a singleton (for example, the real angular service), you could use the accessor class, which instantiates a single instance and returns a reference to callers.

The advantage of this is that you do not need to pollute the instance service (in this case, the function is passed to angular.run), an array of dependencies with the dependencies that are necessary so that they can be passed to PrivateClass ($ enter this case).

I noticed that this is a question for a year, but I found it, looking for a way to achieve just that and ultimately solve it using this approach.

+1
source

Source: https://habr.com/ru/post/982901/


All Articles