Services
Best Practices
Services are Singleton, do use services as singletons within the same injector.
Use them for sharing data and functionality.
Single Responsablility, create services with a single responsability.
Think about every component or service that injects it, and the weight it will carry.
Examples
First step is to add the @Injectable
decorator to show that the class can be injected.
After Angular creates a new instance of a Component, or directive, or pipe class, it determines which service or other dependencies that class needs by looking at the constructor parameter types.
Accessing the service inside a component can be done by:
Either declaring it in the Component
constructor
.Or by using
inject()
. (Newer way)
Circular Dependencies
forwardRef()
forwardRef()
There will be times when an class A
refers to class B
, but class B
also refers to class A
, or when a class C
makes a reference to itself.
This classical problem lies on how one of them will be defined first.
Angular forwardRef()
function resolves this since it creates an indirect reference that Angular can resolve later.
Last updated