angular-services
In this section, we will see how to define and use services.
1. Understanding Angular's Dependency Injection mechanism
Angular uses dependency injection behind the scene to instantiate a service dependency inside a component.
In the following example, we are not directly instantiating the EventService. Angular will find an implementation of this service to be used by our component.
@Component({
...
})
class EventListComponent {
constructor(private eventService: EventService) { }
}
By the way, the previous example is the preferred syntax to use, it is equivalent to the following:
@Component({
...
})
class EventListComponent {
private eventService: EventService;
constructor(eventService: EventService) {
this.eventService = eventService;
}
}
2. Defining a a reusable service
The @Injectable decorator is required if our service has dependencies to other services. In general, we always put it on top of a service definition, it's good practice.
import {Injectable} from '@angular/core';
@Injectable()
class EventService {
constructor(private httpClient: HttpClient) { }
getEvents(): Observable<Event[]> {
return this.httpClient.get<Event[]>(`eventsUrl`);
}
}
3. Making the service available
We need to let the component aware that our new service is now available. To do this, we go to our AppModule and register the service as a provider
@NgModule({
declarations: [
EventsListComponent
],
providers: [EventService],
bootstrap: [EventListComponent]
)}
export class AppModule { }
4. Wrapping Third party services
In this example, we'll use the toastr library.
To install toastr in our project, we just run npm install --save toastr.
Then, in our angular.json file we need to import this npm module by adding the css and js minified file of the library.
{
"styles": [
"src/styles.scss",
"node_modules/toastr/build/toastr.min.css",
"..."
],
"scripts": [
"node_modules/toastr/build/toastr.min.js",
"..."
]
}
We wrap the toastr object and its methods by defining the following custom service:
import {Injectable} from '@angular/core';
declare let toastr: any;
@Injectable()
export class ToastrService {
success(message: string, title?: string) {
toastr.success(message, title);
}
info(message: string, title?: string) {
toastr.info(message, title);
}
warning(message: string, title?: string) {
toastr.warning(message, title);
}
error(message: string, title?: string) {
toastr.error(message, title);
}
}