When is it necessary to use AngularJS factory with Typescript?

I have an application with AngularJS and TypeScript

I want to know if there is any case when I should use AngularJS factory instead of TypeScript Static class

+5
source share
3 answers

Nothing changes with ES6 / TypeScript classes. It is just syntactic sugar for JavaScript constructor functions.

Good options for using factory services can be clarified by the troubleshooting process.

Since service services are preferred for units with OOP flavoring:

 class FooClass { static $inject = [...]; constructor(...) {} } app.service('foo', FooClass); 

And value services are preferred for single units that are not built from classes and are not related to DI:

 app.value('bar', 'bar'); app.value('Baz', BazClass); 

factory services can be used for other cases. That is, when a service requires a DI and the return value cannot be easily constructed from a class - a function, primitive, an object that is returned from a function call:

 app.factory('qux', ($q) => $q.all([...])); 
+3
source

We had the same problem two years ago. The solution was to stay with the angular system and only build the angular services. Neither angular factory, or typescript static. The reason is that we could keep track of how the service was created and distributed. (tough)

To answer your question, angular factory is an object that still needs an injection base in the angular system. Well, if you want to keep in touch with angular.

Typescript, on the other hand, is more general. When you call a static function, it is just a function. How can you import it somewhere else is not angular, and then use it.

+3
source

Something about javascript template:

A common template for creating objects in JavaScript is the module template. The template includes returning an object from a function that will be a public API.

There is a popular variation on the module template called the expand module template. What happens to the module’s drop-down template is that things become explicitly private, and then decisions are made about whether they become publicly available.

+1
source

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


All Articles