Services
ng g service [service-name] [options]
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.
// For local level services - available to the Component (USING ElementInjector)
@Injectable()
export class LocalService { ... }
// Or
// For root level services - available everywhere (USING root EnvironmentInjector)
@Injectable({
providedIn: "root",
})
export class SomeService { ... }
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)
@Component({
providers: [LocalService]
})
export class Component {
// Declare it in the constructor
constructor(private someService: SomeService, private localService: LocalService) {}
// Or by calling `inject()`
private someService = inject(SomeService);
private localService = inject(LocalService);
someFunction() {
this.someService.serviceMethod();
this.localService.serviceMethod();
}
}
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.
@Component({
providers: [
{
provide: PARENT_MENU_ITEM,
useExisting: forwardRef(() => MenuItem),
},
]
})
Last updated