Set Up Angular CLI
To install the Angular project, you need to have latest version of Angular CLI installed.npm install -g @angular/cli@latestIn case of error prefix `sudo` with the above command and provide admin password.
Setting Up Angular Project
Run the below command to install the brand new Angular project.
ng new angular-service-exampleRun command to get inside the project folder.
cd angular-service-exampleStart the application in the browser.
ng serve --openCreating Service Class
ng generate service crudAbove command creates the following files in the src/app folder.
# src/app/crud.service.spec.tsHere, is the file crud.service.ts file we generated for Angular Service example.
# src/app/crud.service.ts
import { Injectable } from '@angular/core';@Injectable(): Decorator that marks a class as available to be provided and injected as a dependency.
@Injectable({
providedIn: 'root'
})
export class CrudService {
constructor() { }
}
Next, we need to import the Service Class in the app.module.ts, and also register the service class in the providers array.
// Service classCreating Methods in Service Class
import { CrudService } from './crud.service';
@NgModule({
declarations: [...],
imports: [...],
providers: [CrudService],
bootstrap: [...]
})
To make these methods work you also need to import and register HttpClientModule in the main app module file.
import { HttpClientModule } from '@angular/common/http';In the API section you need to pass the API URL in order to make this API work.
@NgModule({
imports: [
HttpClientModule
]
})
import { Injectable } from '@angular/core';Access Service Methods in Components
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CrudService {
apiUrl: string = 'enter-your-api-url';
headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http: HttpClient) { }
// Create
createTask(data): Observable<any> {
let API_URL = `${this.apiUrl}/create-task`;
return this.http.post(API_URL, data)
.pipe(
catchError(this.error)
)
}
// Read
showTasks() {
return this.http.get(`${this.apiUrl}`);
}
// Update
updateTask(id, data): Observable<any> {
let API_URL = `${this.apiUrl}/update-task/${id}`;
return this.http.put(API_URL, data, { headers: this.headers }).pipe(
catchError(this.error)
)
}
// Delete
deleteTask(id): Observable<any> {
var API_URL = `${this.apiUrl}/delete-task/${id}`;
return this.http.delete(API_URL).pipe(
catchError(this.error)
)
}
// Handle Errors
error(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
}
import { CrudService } from './crud.service';Next, we need to follow the dependency injection pattern and inject the Service class inside the constructor.
export class AppComponent {Next, we can easily access all the CrudService methods, and we are using the ngOnInit() lifecycle hook to access the showTask() method of Angular Service class.
constructor(private crudService: CrudService){}
}
import { Component, OnInit } from '@angular/core';
import { CrudService } from './crud.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private crudService: CrudService) { }
ngOnInit() {
console.log(this.crudService.showTasks);
}
}