Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases there is need to use of AngularJS factory with Typescript?

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

like image 753
Anton Temchenko Avatar asked Mar 09 '23 14:03

Anton Temchenko


2 Answers

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([...]));
like image 61
Estus Flask Avatar answered Mar 16 '23 01:03

Estus Flask


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.

like image 22
robert Avatar answered Mar 16 '23 01:03

robert