Services are useful to organize your code in domains. They can be used in a wide variety of situations: logging, interaction with a database, calculations, communication with an external API, etc.
Basically, a service can be any class with a narrow and well defined purpose. They are instantiated as singletons.
You can access a service from a controller using the
When instantiating the controller, FoalTS will provide the service instance. This mechanism is called dependency injection and is particularly interesting in unit testing (see section below).
In the same way, you can access a service from another service.
Dependencies are injected after the instantiation of the controller/service. So they will appear as
undefinedif you try to read them inside a constructor. If you want to access the dependencies when initializing a controller/service, refer to the
Circular dependencies are not supported. In most cases, when two services are dependent on each other, the creation of a third service containing the functionalities required by both services solves the dependency problem.
Services are classes and so can be tested as is.
If your service has dependencies, you can use the
createService function to instantiate the service with them.
A similar function exists to instantiate controllers with their dependencies:
In many situations, it is necessary to mock the dependencies to truly write unit tests. This can be done by passing a second argument to
To manually inject instances into the identity mapper, you can also provide your own
ServiceManager to the
createApp function (usually located at
Note: Interfaces cannot be passed to the
If you want to use a different service implementation depending on your environment (production, development, etc.), you can use an abstract service for this.
Warning: the two properties must be static.
console-logger.service.ts (concrete service)
The configuration value can be a package name or a path relative to the
src/directory. If it is a path, it must start with
./and must not have an extension (
a random service
An abstract service can have a default concrete service that is used when no configuration value is specified or when the configuration value is
Interfaces and generic classes can be injected using strings as IDs. To do this, you will need the
In very rare situations, you may want to access the
ServiceManager which is the identity mapper that contains all the service instances.