To create an injectable service with Angular, follow these steps:
- Open your Angular project in your favorite code editor.
- Create a new TypeScript file for your service. For example, create a file called
my-service.service.ts
in thesrc/app
directory of your project. - In your TypeScript file, import the
Injectable
decorator from@angular/core
. TheInjectable
decorator is used to mark a class as an injectable service.
import { Injectable } from '@angular/core';
- Add the
@Injectable()
decorator to your service class. This decorator tells Angular that this class can be injected with dependencies.
@Injectable()
export class MyService {
// Your service code goes here
}
- Write your service code inside the
MyService
class. For example, you can define a method that returns some data.
@Injectable()
export class MyService {
getData(): string {
return 'Hello, World!';
}
}
Save the TypeScript file.
In your Angular component, import your service and add it to the providers
array in the @Component
decorator. For example:
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'],
providers: [MyService]
})
export class MyComponent {
constructor(private myService: MyService) {}
// Use the service in your component code
data = this.myService.getData();
}
That’s it! You have created an injectable service with Angular and injected it into a component. Now you can use the service in your component code to get data or perform other tasks.