Wednesday, January 8, 2020

Angular 8/9 Service Tutorial with Example

Set Up Angular CLI
To install the Angular project, you need to have latest version of Angular CLI installed.
npm install -g @angular/cli@latest
In case of error prefix `sudo` with the above command and provide admin password.
Angular 8/9 Service Tutorial with Example

Setting Up Angular Project
Run the below command to install the brand new Angular project.
ng new angular-service-example
Run command to get inside the project folder.
cd angular-service-example
Start the application in the browser.
ng serve --open
Creating Service Class
ng generate service crud
Above command creates the following files in the src/app folder.
# src/app/crud.service.spec.ts
# src/app/crud.service.ts
Here, is the file crud.service.ts file we generated for Angular Service example.
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class CrudService {
  constructor() { }
 
}
@Injectable(): Decorator that marks a class as available to be provided and injected as a dependency.

Next, we need to import the Service Class in the app.module.ts, and also register the service class in the providers array.
// Service class
import { CrudService } from './crud.service';
@NgModule({
  declarations: [...],
  imports: [...],
  providers: [CrudService],
  bootstrap: [...]
})
Creating Methods in Service Class
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';
@NgModule({
  imports: [
    HttpClientModule
   ]
})
In the API section you need to pass the API URL in order to make this API work.
import { Injectable } from '@angular/core';
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);
  }
}
Access Service Methods in Components
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 {
  constructor(private crudService: CrudService){}
}
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.
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);
  }
}