Creating a Service with Angular CLI
Demonstrate the command for generating a new service and how to inject it into a component for data management.
ng generate service data
Run this command in the Angular CLI to create a new service named DataService.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class DataService {
constructor() { }
// Method to get data (example)
getData() {
// Logic to fetch or manipulate data
}
// Other data management methods
}
This is the generated DataService class with a placeholder method for getting data. It is marked as Injectable, indicating that it can be injected into other classes, like components.
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
constructor(private dataService: DataService) { }
ngOnInit() {
// Use the service to get data when the component initializes
this.dataService.getData();
}
}
This is an Angular component where the DataService is injected through the constructor. The 'ngOnInit' lifecycle hook is used to call a method on the service to get data when the component is initialized.