Services
Services are injectable classes that are used to perform reusable logic. This helps us to have much cleaner and easy to maintain components. It is recommended that all http requests and business logic are made inside a service.
Create a service
To create a service, we can use the cli to automatically generate a service file with boilerplate codes or we can manually create a file and write the code from scratch.
The following code is an example of a working service codes but without functions yet.
import { Service } from '@monster-js/core';
@Service()
export class GreetingService {
}
Singleton service
Services is transient by default.
To create a singleton service, we need to pass an optional config to @Service()
decorator.
The config is an object that contains a singleton
property that is set to true.
Example.
import { Service } from '@monster-js/core';
@Service({ singleton: true })
export class GreetingService {
}
Register service in component
Before we can use a service we need to register it in our component.
Example.
import { component, providers } from '@monster-js/core';
import { GreetingService } from './greeting.service';
export function greeting() {
return <h1>Greeting</h1>
}
component(greeting, 'app-greeting');
providers(greeting, GreetingService);
Register service in module
If multiple components in a module are using the service it is recommended that we register the service in our module. Services registered in a module will be available to all the components registered in the same module.
Example.
import { Module } from '@monster-js/core/module';
import { GreetingService } from './greeting.service';
export const GreetingModule: Module = {
providers: [GreetingService]
};
Register service as a global service
If we want our service to be available to all our components inside our application, we can also register the service as a global service.
Example.
import { globalProvider } from '@monster-js/core';
import { GreetingService } from './greeting.service';
globalProvider(GreetingService);