Angular services are singleton objects that are instantiated only once during the lifetime of an application. They are used to encapsulate business logic, data access, and other functionalities that can be shared across components.
To create a service in Angular, you can use the Angular CLI. Run the following command:
ng generate service my-service
This will create a new service file named `my-service.service.ts` in your project.
To use a service in a component, you need to inject it into the component's constructor. For example:
import { MyService } from './my-service.service';
@Component({
...
})
export class MyComponent {
constructor(private myService: MyService) { }
}
Once injected, you can use the service methods in your component. For example:
this.myService.getData().subscribe(data => {
console.log(data);
});