I have an app with AngularJS and TypeScript
I want to know is there any case when I should use AngularJS factory instead of TypeScript Static Class
Nothing changes with ES6/TypeScript classes. They are just syntactic sugar for JavaScript constructor functions.
Good use cases for factory
services can be figured out by the process of elimination.
Since service
services are preferable for OOP-flavoured units:
class FooClass {
static $inject = [...];
constructor(...) {}
}
app.service('foo', FooClass);
And value
services are preferable for singleton units that aren't constructed from classes and don't involve DI:
app.value('bar', 'bar');
app.value('Baz', BazClass);
factory
services can be used for the rest of the cases. I.e. when a service needs DI and returned value cannot be easily constructed from a class - a function, a primitive, an object that is returned from function call:
app.factory('qux', ($q) => $q.all([...]));
We had same problem two years ago. The decision was to stay with angular system and only build angular services. Neither angular factory or typescript static. The reason was we could track how service has been created and shared. (by hard)
To answer your question, angular factory is an object which still need injection base on angular system. It is good if you would like keep tight with angular.
On the other hand typescript is more general. When you call a static function, it is just a function. Like you can import it anywhere else not angular, and then use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With