57 lines
2.4 KiB
Markdown
57 lines
2.4 KiB
Markdown
# Services and dependency injection
|
|
|
|
A service prevents code duplication (LogService) or handlich with data (UserService - Data Sotrage).
|
|
|
|
## Create a logging service from
|
|
|
|
Naming: `logging.service.ts`
|
|
|
|
> Instanciate a service manually with method `new` is the wrong way! Angular offers a much better solution.
|
|
|
|
## Dependency injection
|
|
|
|
Angular is responsable to instanciate the service which is passed as argument to the constructor. Which tels Angular thet the LoggingService is required.
|
|
|
|
```ts
|
|
import { LoggingService } from '../logging.service.ts';
|
|
|
|
@Component({
|
|
...
|
|
providers: [LoggingService]
|
|
})
|
|
|
|
export class NewAccountComponent {
|
|
|
|
constructor(private loggingService: LoggingService) {}
|
|
|
|
function(){
|
|
// Calling the loggingService
|
|
// logStatusChange is a function in the loggingService which accepts a string as argument.
|
|
this.loggingService.logStatusChange(accountStatus);
|
|
}
|
|
}
|
|
```
|
|
|
|
`private loggingService` makes directly a property of type `LoggingService` and with the `provider` in the `@Component`-decorator, angular instanciate the logging service.
|
|
|
|
## Hierarchical Injector
|
|
|
|
By instanciate a service, Angular provides the same Instance to the component and all its childs.
|
|
|
|
| Level | Description |
|
|
| ------------------- | --------------------------------------------------------------------------------------------- |
|
|
| AppModule | Service is available **Application-wide** |
|
|
| AppComponent | Same instance of service is available for **all Components** (but **not for other services**) |
|
|
| Any other Component | Same instance of Service is available for **the Component and all its chilf component** |
|
|
|
|
By declare the service in a lower component, will create a new instance and override the inherited from the parents one.
|
|
|
|
It is necessary to declare it in the `impot` and in the `constructor`.
|
|
|
|
`app.module.ts` is the highest level to declare a service. This opens the possibility to inject services into an other service.
|
|
|
|
To the service who will be injected a service, is necessaty to provide metadata. Its keyword is `@Injectable()`
|
|
|
|
Services can also be used to avoiding data/event/listener chaining.
|
|
|
|
By Implementing the event in the service, and the listener in the component, can mitigate the chaining. |