AngularJS services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.
AngularJS services are:
Lazily instantiated – AngularJS only instantiates a service when an application component depends on it.
Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
AngularJS offers several useful services (like $http), but for most applications you’ll also want to create your own.
Logging Service
Example can be logging service. Create file app/logging.service.ts:
We can store data in a service, for example array of accounts.
app/accounts.service.ts
app/app.component.ts
!IMPORTANT In this file AccountsService isnt in providers. Thats because when you put service into providers, you are creating new instance. And we want to use instance which was created in app.component.ts, the same array of accounts.
new-account.components.ts
Service in app.module.ts
There is providers also in app.module.ts. Put your services here if you want to have it available in whole app.
Injecting Service in Service
If we want to use Service inside another Service. We need firt to import it, make constructor and use @Injectable.