What is a service?

A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.

Let's create a repoService which can be used across components,

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({
// The Injectable decorator is required for dependency injection to work
// providedIn option registers the service with a specific NgModule
providedIn: 'root', // This declares the service with the root app (AppModule)
})
export class RepoService {
constructor(private http: Http) {}
fetchAll() {
return this.http.get('https://api.github.com/repositories');
}
}

The above service uses Http service as a dependency.


August 29, 2022
700