Basics Of Angular And Its Versions - Part Three

More on Services

Before reading this article, first of all, please have a look at my previous articles (Part one and Part two) for better understanding.

In this article, I am going to explain more about one of the 8 main building blocks of Angular, that is, Services. In my previous article, I just explained what is it. Here, we will try to understand a little more with examples.

As I told you in my previous article, the created services need to be registered before we use them. To bring that statement with examples, please follow the below steps.

Step #1

First, I want to create a common proxy service class with HTTP verbs with unique signatures so that they can be used for all types of service requests throughout the application.

Below is the sample code snippet for the common proxy service class where we can define HTTP verbs with different signatures.

  1. import { Injectable } from '@angular/core';  
  2. import { Headers, Http, RequestOptionsArgs, RequestMethod, Request, Response } from '@angular/http';  
  3. import 'rxjs/add/operator/toPromise';  
  4. import { Router } from '@angular/router';  
  5.   
  6. import { environment } from '../../../../environments/environment';  
  7. import { SessionService } from '../SessionService/session.service';  
  8. import {Logger} from 'angular2-logger/core';  
  9.   
  10. @Injectable()  
  11. export class ProxyService {  
  12.   
  13.     constructor(private http: Http, private router: Router, private _logger: Logger) {  
  14.     }  
  15.   
  16.     /** 
  17.      * Perform GET request. 
  18.      * 
  19.      * @param uri Request or Relative URL specifying the destination of the request 
  20.      */  
  21.     get(uri: string | Request): Promise<any> {  
  22.         return this.request(this.newRequest(RequestMethod.Get, uri));  
  23.     }  
  24.   
  25.     /** 
  26.      * Perform DELETE request. 
  27.      * 
  28.      * @param uri Request or Relative URL specifying the destination of the request 
  29.      */  
  30.     delete(uri: string | Request): Promise<any> {  
  31.         return this.request(this.newRequest(RequestMethod.Delete, uri));  
  32.     }  
  33.   
  34.     /** 
  35.      * Perform POST request. 
  36.      * 
  37.      * @param uri Request or Relative URL specifying the destination of the request 
  38.      * @param body Request content 
  39.      */  
  40.     post(uri: string | Request, body: any): Promise<any> {  
  41.         return this.request(this.newRequest(RequestMethod.Post, uri, body));  
  42.     }  
  43.   
  44.     /** 
  45.      * Perform PUT request. 
  46.      * 
  47.      * @param uri Request or Relative URL specifying the destination of the request 
  48.      * @param body Request content 
  49.      */  
  50.     put(uri: string | Request, body: any): Promise<any> {  
  51.         return this.request(this.newRequest(RequestMethod.Put, uri, body));  
  52.     }  
  53.   
  54.     /** 
  55.      * Create a new http request for customization. 
  56.      * 
  57.      * @param method request type 
  58.      * @param uri to web service to prepended with configuration api endpoint 
  59.      * @param body request data 
  60.      * @returns {Request} 
  61.      */  
  62.     private blankRequest(method: RequestMethod, uri: string | Request, body?: any): Request {  
  63.         let req: Request;  
  64.   
  65.         if (typeof uri === 'string') {  
  66.             req = new Request(<any>{  
  67.                 method: method,  
  68.                 url: uri,  
  69.                 body: body  
  70.             });  
  71.         } else {  
  72.             req = <Request>uri;  
  73.         }  
  74.   
  75.         return req;  
  76.     }  
  77.   
  78.     /** 
  79.      * Create a new http request for customization and add session tokens to header. 
  80.      * 
  81.      * @param method request type 
  82.      * @param uri to web service to prepended with configuration api endpoint 
  83.      * @param body request data 
  84.      * @returns {Request} 
  85.      */  
  86.     private newRequest(method: RequestMethod, uri: string | Request, body?: any): Request {  
  87.         let req: Request;  
  88.   
  89.         if (typeof uri === 'string') {  
  90.             req = this.blankRequest(method, uri, body);  
  91.             req.headers = new Headers();  
  92.         } else {  
  93.             req = <Request>uri;  
  94.             req.headers = req.headers || new Headers();  
  95.         }  
  96.   
  97.         req.url = environment.apiEndpoint + environment.apiPrefix + req.url;  
  98.         const sessionID = this.sessionService.getSessionID();  
  99.         if (sessionID) {  
  100.             req.headers.append(environment.sessionTokenName, sessionID);  
  101.         }  
  102.         if(body){  
  103.             req.headers.append('Content-Type''text/json');  
  104.             req.headers.append('Accept''text/json');  
  105.         }  
  106.         return req;  
  107.     }  
  108.   
  109.     /** 
  110.      * Handle error with error logging. 
  111.      * 
  112.      * For 401 clear session token and redirect to the login page. 
  113.      * 
  114.      * @param error result from http request 
  115.      * @param req original request 
  116.      * @returns {Promise<Response>} 
  117.      */  
  118.     private handleError(error: any, req: Request): Promise<Response> {  
  119.         if (error.status && error.status === 401) {  
  120.             this.sessionService.removeSessionID();  
  121.             this.router.navigate(['/login']);  
  122.         } else {  
  123.             this._logger.error('An error occurred' + JSON.stringify(req, null, 2) + error);  
  124.         }  
  125.   
  126.         return Promise.reject(error.message || error);  
  127.     }  
  128.   
  129.     /** 
  130.      * Perform given request only using prepopulated request Request. 
  131.      * 
  132.      * @param req Request 
  133.      */  
  134.     private request(req: Request): Promise<any> {  
  135.         return this.http.request(req)  
  136.             .toPromise()  
  137.             .then((response: Response) => {  
  138.                 return response.text().length ? response.json() : null;  
  139.             })  
  140.             .catch((error: any) => this.handleError(error, req));  
  141.     }  
  142. }  

Step #2

Now, the created common proxy service class needs to be registered to a root module. We do this to it so that it can be available throughout the application.

src\app\core\ core.module.ts

  1. import { ProxyService } from './services/ProxyService/proxy.service';  
  2.   
  3. @NgModule({  
  4.     imports: [          
  5.     ],  
  6.     declarations: [          
  7.     ],  
  8.     providers: [  
  9.         ProxyService          
  10.     ],  
  11.     exports: [  
  12.        ],  
  13.     entryComponents: [      
  14.     ]  
  15. })  
  16. export class CoreModule {  

Step #3

Once the common proxy service is created and registered in the root module, we can use it in any service creation by simply importing and injecting it as a dependency injection in the constructor of the newly created Service class.

Below is the sample code snippet for the service class creation and utilization of the common proxy service class inside newly created service class.

  1. import { Observable } from 'rxjs/Rx';  
  2. import { Injectable } from '@angular/core';  
  3. import { ProxyService } from 'app/core/services/ProxyService/proxy.service';  
  4. @Injectable()  
  5. export class TestService {  
  6.   constructor(private proxyService: ProxyService) { }  
  7.   // post data to Api  
  8.   saveTestCode(casePayment: any): Observable<any> {  
  9.     return Observable.fromPromise(this.proxyService.put('TestCode/UpsertTestCode', testId));  
  10.   }  
  11.   getTestCode(testId: number): Observable<any> {  
  12.     return Observable.fromPromise(this.proxyService.get(TestCode/GetTestCodeById?testId=' + testId));  
  13.   }  
  14. }   

In my upcoming articles, I am going to show you a demo application to demonstrate all our learnings on Angular.  

I would appreciate your valuable comments.

Up Next
    Ebook Download
    View all
    Learn
    View all