Welcome to this comprehensive guide on creating services in Angular! This tutorial is designed for both beginners and intermediate learners, so let's dive right in.
Services in Angular are classes that provide a collection of loosely coupled, reusable functions. They help organize your application by encapsulating functionality that can be shared across components, directives, pipes, and other services.
Let's create a simple service that returns a greeting message.
import { Injectable } from '@angular/core';
@Injectable()
export class GreetingService {
getGreeting() {
return 'Hello, Angular!';
}
}In this example, we've created a GreetingService that has a single function, getGreeting(), which returns a greeting message.
@Injectable() to indicate that it can be injected into other parts of our application.To use our GreetingService, we'll inject it into a component and call its getGreeting() function.
import { Component, OnInit } from '@angular/core';
import { GreetingService } from './greeting.service';
@Component({
selector: 'app-root',
template: `
<h1>{{ greeting }}</h1>
`,
})
export class AppComponent implements OnInit {
greeting: string;
constructor(private greetingService: GreetingService) {}
ngOnInit() {
this.greeting = this.greetingService.getGreeting();
}
}In this example, we've injected our GreetingService into our AppComponent using the constructor. We've then called its getGreeting() function in the ngOnInit() lifecycle hook and stored the result in our greeting property.
What does `@Injectable()` do in an Angular service?
In this tutorial, we've learned about Angular services, why they're useful, and how to create and use them. Services help organize your code and provide a way to share functionality across your application.
In the next lesson, we'll dive deeper into services and learn how to share data between components using services. Stay tuned!