Frontend
Angular
Angular questions
What is a service in Angular and how is it created and injected into a component?

What is a service in Angular and how is it created and injected into a component?

A service in Angular is a class that contains reusable logic and can be injected into components or other services. It is created with the @Injectable decorator and injected using the component's constructor.

For example:

import { Injectable } from '@angular/core';
 
@Injectable({
  providedIn: 'root',
})
export class MyService {
  getValue() {
    return 'Hello from service!';
  }
}
 
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
 
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  value: string;
 
  constructor(private myService: MyService) {
    this.value = this.myService.getValue();
  }
}