Exploring Angular Services

 

Services in Angular is meant for specifically making the call to RestFul API and getting the data and passing data to all component which ever component subscribe it. Moreover it gives us the benefit of code reusability and data sharing across components.

Goals

  1. How to create a basic service in Angular
  2. How to subscribe the service response.
  3. How to handle error in service.

Specifications

In this tutorial , we will create a basic angular application and try to use service to get data and pass the data component.

Why Services

Basically component is meant for providing the data to view, when I say view means providing the data to respective HTML whatever is required, it is not a good practice to make a api call directly from component. Services gives the benefit of separation of concerns and you can say single responsibility principle as well.

Let see services in action

  1. Create angular project :go to VS code integrated terminal
    1. Run - ng new ServiesTest
  2. Run this newly created project by using below command
    1. ng serve
    Once you run this command you must see below page at http://localhost:4200/
  3. Create a service by using below command
    1. ng g s DateTime
  4. Now go to DateTimeService.ts file you will find below code
    1. import { Injectable } from '@angular/core';
    2.  
    3. @Injectable({
    4. providedIn: 'root'
    5. })
    6. export class DateTimeService {
    7.  
    8. constructor() { }
    9. }
    If you notice it has the @Injectable decorator similar to @Component decorator what we use to have in a angular component. @Injectable means it can participate in dependency injection, those who don't know dependency injection I will explain it in my next article as it is not the topic of this discussion, it need further explanation, so will keep that in separate article.@Injectable accepts metadata object. So here you can providedIn value as root , which means this service can be injected in any of the class across the project.
  5. Now let us write the code to consume actual service.So here I am trying to call a real-time RestFul API which is fromhttps://www.jsontest.com/
  6. We will call a API located at : http://date.jsontest.com So here is the code for same :
    1. import { Injectable } from '@angular/core';
    2.  
    3. @Injectable({
    4. providedIn: 'root'
    5. })
    6. export class DateTimeService {
    7.  
    8. public apiURL:string="http://date.jsontest.com";
    9. constructor() { }
    10.  
    11. getDateTime ()
    12. {
    13. return this.httpClient.get(this.apiURL)
    14. .pipe(
    15. map(res => res),
    16. catchError( this.errorHandler)
    17. );
    18. }
    19.  
    20. }
    So my code is complaining about httpClient, map, catchError, and errorHandler.
  7. So let us do import for these complain.
    1. import { HttpClient } from '@angular/common/http';
    For httpClient and inject in constructor like below :
    1. constructor(private httpClient:HttpClient) { }
    2. import { map, catchError } from 'rxjs/operators';
    3. For map, catchError
    4. Now it's time to fix errorHandler.
    5. So write one method like below:
    6.  
    7. errorHandler(error: Response) {
    8. console.log(error);
    9. return throwError(error);
    10. }
    Lastly do this import :
    1. import {throwError} from 'rxjs'
    So finally service code looks like this :
    1. import { Injectable } from '@angular/core';
    2. import { HttpClient } from '@angular/common/http';
    3. import {throwError} from 'rxjs'
    4. import { map, catchError } from 'rxjs/operators';
    5.  
    6. @Injectable({
    7. providedIn: 'root'
    8. })
    9. export class DateTimeService {
    10.  
    11. public apiURL:string="http://date.jsontest.com";
    12. constructor(private httpClient:HttpClient) { }
    13.  
    14. getDateTime ()
    15. {
    16. return this.httpClient.get(this.apiURL)
    17. .pipe(
    18. map(res => res),
    19. catchError( this.errorHandler)
    20. );
    21. }
    22. errorHandler(error: Response) {
    23. console.log(error);
    24. return throwError(error);
    25. }
    26. }
    If any error while calling the service it will be logged in console and error will thrown to the subscriber.Now it is the time to consume this service from the component.So here you go.
    Go to app.module.ts and import
    1. import { HttpClient,HttpClientModule } from '@angular/common/http';
    Use this import in import array like this
    1. imports: [
    2. BrowserModule,HttpClientModule
    3. ],
    First of all you need to inject this service in component like this :
    1. constructor(private dateTimeService:DateTimeService){}
    So here now by using this dateTimeService injector we will call the service method like this
    1. ngOnInit()
    2. {
    3. this.dateTimeService.getDateTime()
    4. .subscribe((result) => {
    5. this.globalResponse = result;
    6. },
    7. error => { //This is error part
    8. console.log(error.message);
    9. },
    10. () => {
    11. // This is Success part
    12. console.log("Date time fetched sucssesfully.");
    13. console.log(this.globalResponse);
    14. }
    15. )
    16.  
    17. }
    Here we are calling getDateTime method from service , which will call http://date.jsontest.com and return us back output in below format.
    1. {
    2. "time": "03:53:25 AM",
    3. "milliseconds_since_epoch": 1362196405309,
    4. "date": "03-02-2013"
    5. }
    We are subscribing the service response here in component, similarly in this way you can consume this service in any of your component because service is injected in root. So in my component, as you can see I am storing the service response in global response. Since we have logged the service response in console , so you can see response in console something like this.
    Let us bind this variable to HTML. Go to app.component.html and paste this code :
    1. style="text-align:center">
    2. Welcome to !

  • Current date
  • Current Time

  • And run the project , your output will be like this
    Now let me give all required files source code :
    App.module.ts
    1. import { BrowserModule } from '@angular/platform-browser';
    2. import { NgModule } from '@angular/core';
    3. import { HttpClient,HttpClientModule } from '@angular/common/http';
    4.  
    5. import { AppComponent } from './app.component';
    6.  
    7. @NgModule({
    8. declarations: [
    9. AppComponent
    10. ],
    11. imports: [
    12. BrowserModule,HttpClientModule
    13. ],
    14. providers: [],
    15. bootstrap: [AppComponent]
    16. })
    17. export class AppModule { }
    18.  
    19.  
    20. date-time.service.ts:
    21. import { Injectable } from '@angular/core';
    22. import { HttpClient } from '@angular/common/http';
    23. import {throwError} from 'rxjs'
    24. import { map, catchError } from 'rxjs/operators';
    25.  
    26. @Injectable({
    27. providedIn: 'root'
    28. })
    29. export class DateTimeService {
    30.  
    31. public apiURL:string="http://date.jsontest.com";
    32. constructor(private httpClient:HttpClient) { }
    33.  
    34. getDateTime ()
    35. {
    36. return this.httpClient.get(this.apiURL)
    37. .pipe(
    38. map(res =>res),
    39. catchError( this.errorHandler)
    40. );
    41. }
    42. errorHandler(error: Response) {
    43. console.log(error);
    44. return throwError(error);
    45. }
    46. }
    app.component.ts
    1. import { Component,OnInit } from '@angular/core';
    2. import { DateTimeService } from './date-time.service';
    3.  
    4. @Component({
    5. selector: 'app-root',
    6. templateUrl: './app.component.html',
    7. styleUrls: ['./app.component.css']
    8. })
    9. export class AppComponent implements OnInit {
    10. title = 'DotNet Techy YouTube Channel Services in Angular 6 Demo';
    11. public globalResponse: any;
    12. constructor(private dateTimeService:DateTimeService){}
    13.  
    14. ngOnInit()
    15. {
    16. this.dateTimeService.getDateTime()
    17. .subscribe((result) => {
    18. this.globalResponse = result;
    19. },
    20. error => { //This is error part
    21. console.log(error.message);
    22. },
    23. () => {
    24. // This is Success part
    25. console.log("Date time fetched sucssesfully.");
    26. console.log(this.globalResponse);
    27. console.log("Thanks to DotNet Techy Youtube channel who taught me, how to create services in Angular 6.");
    28. }
    29. )
    30.  
    31. }
    32. }
    app.component.html
    1. style="text-align:center">
    2. Welcome to !

  • Current date
  • Current Time

  • Summary
    Similarly you can use post, put,delete as well. It is so simple, if any doubt comment on article I will help you on that.

    Comments

    Popular posts from this blog

    How to Build a Mobile App like Instagram

    CONSTRUCTION TECHNOLOGY AND NATIONAL DEVELOPMENT

    2018 Jamb Admission Status For UTME and DE