Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Services in Components in Angular

Services in Angular are used to share data and logic across different components. This tutorial covers the basics of using services effectively in your Angular components.

Creating a Service

Create a service using the Angular CLI command ng generate service my:

$ ng generate service my

This command creates a new service file named my.service.ts in your project.

Implementing the Service

In the service file, use the @Injectable decorator to make the service available for dependency injection:

// my.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }

  getMessage(): string {
    return 'Hello from MyService!';
  }
}

Using the Service in a Component

Inject the service into your component's constructor and use it in the component's logic:

// home.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';

@Component({
  selector: 'app-home',
  template: '

{{ message }}

', }) export class HomeComponent implements OnInit { message: string; constructor(private myService: MyService) {} ngOnInit() { this.message = this.myService.getMessage(); } }

Providing the Service

Services can be provided at the root level or in specific modules. Using providedIn: 'root' ensures that the service is a singleton and available application-wide:

// my.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }

  getMessage(): string {
    return 'Hello from MyService!';
  }
}

Injecting the Service

To use the service in your component, inject it into the component's constructor:

// home.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';

@Component({
  selector: 'app-home',
  template: '

{{ message }}

', }) export class HomeComponent implements OnInit { message: string; constructor(private myService: MyService) {} ngOnInit() { this.message = this.myService.getMessage(); } }

Key Points

  • Create a service using the Angular CLI command ng generate service my.
  • Use the @Injectable decorator to make the service available for dependency injection.
  • Inject the service into your component's constructor to use it in the component's logic.
  • Provide the service at the root level using providedIn: 'root' to ensure it is a singleton and available application-wide.

Conclusion

Using services in Angular components allows you to share data and logic across your application. By understanding and using services effectively, you can create modular and maintainable code. Happy coding!