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.
- import { Injectable } from '@angular/core';
- import { Headers, Http, RequestOptionsArgs, RequestMethod, Request, Response } from '@angular/http';
- import 'rxjs/add/operator/toPromise';
- import { Router } from '@angular/router';
- import { environment } from '../../../../environments/environment';
- import { SessionService } from '../SessionService/session.service';
- import {Logger} from 'angular2-logger/core';
- @Injectable()
- export class ProxyService {
- constructor(private http: Http, private router: Router, private _logger: Logger) {
- }
- /**
- * Perform GET request.
- *
- * @param uri Request or Relative URL specifying the destination of the request
- */
- get(uri: string | Request): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Get, uri));
- }
- /**
- * Perform DELETE request.
- *
- * @param uri Request or Relative URL specifying the destination of the request
- */
- delete(uri: string | Request): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Delete, uri));
- }
- /**
- * Perform POST request.
- *
- * @param uri Request or Relative URL specifying the destination of the request
- * @param body Request content
- */
- post(uri: string | Request, body: any): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Post, uri, body));
- }
- /**
- * Perform PUT request.
- *
- * @param uri Request or Relative URL specifying the destination of the request
- * @param body Request content
- */
- put(uri: string | Request, body: any): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Put, uri, body));
- }
- /**
- * Create a new http request for customization.
- *
- * @param method request type
- * @param uri to web service to prepended with configuration api endpoint
- * @param body request data
- * @returns {Request}
- */
- private blankRequest(method: RequestMethod, uri: string | Request, body?: any): Request {
- let req: Request;
- if (typeof uri === 'string') {
- req = new Request(<any>{
- method: method,
- url: uri,
- body: body
- });
- } else {
- req = <Request>uri;
- }
- return req;
- }
- /**
- * Create a new http request for customization and add session tokens to header.
- *
- * @param method request type
- * @param uri to web service to prepended with configuration api endpoint
- * @param body request data
- * @returns {Request}
- */
- private newRequest(method: RequestMethod, uri: string | Request, body?: any): Request {
- let req: Request;
- if (typeof uri === 'string') {
- req = this.blankRequest(method, uri, body);
- req.headers = new Headers();
- } else {
- req = <Request>uri;
- req.headers = req.headers || new Headers();
- }
- req.url = environment.apiEndpoint + environment.apiPrefix + req.url;
- const sessionID = this.sessionService.getSessionID();
- if (sessionID) {
- req.headers.append(environment.sessionTokenName, sessionID);
- }
- if(body){
- req.headers.append('Content-Type', 'text/json');
- req.headers.append('Accept', 'text/json');
- }
- return req;
- }
- /**
- * Handle error with error logging.
- *
- * For 401 clear session token and redirect to the login page.
- *
- * @param error result from http request
- * @param req original request
- * @returns {Promise<Response>}
- */
- private handleError(error: any, req: Request): Promise<Response> {
- if (error.status && error.status === 401) {
- this.sessionService.removeSessionID();
- this.router.navigate(['/login']);
- } else {
- this._logger.error('An error occurred' + JSON.stringify(req, null, 2) + error);
- }
- return Promise.reject(error.message || error);
- }
- /**
- * Perform given request only using prepopulated request Request.
- *
- * @param req Request
- */
- private request(req: Request): Promise<any> {
- return this.http.request(req)
- .toPromise()
- .then((response: Response) => {
- return response.text().length ? response.json() : null;
- })
- .catch((error: any) => this.handleError(error, req));
- }
- }
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
- import { ProxyService } from './services/ProxyService/proxy.service';
- @NgModule({
- imports: [
- ],
- declarations: [
- ],
- providers: [
- ProxyService
- ],
- exports: [
- ],
- entryComponents: [
- ]
- })
- 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.
- import { Observable } from 'rxjs/Rx';
- import { Injectable } from '@angular/core';
- import { ProxyService } from 'app/core/services/ProxyService/proxy.service';
- @Injectable()
- export class TestService {
- constructor(private proxyService: ProxyService) { }
- // post data to Api
- saveTestCode(casePayment: any): Observable<any> {
- return Observable.fromPromise(this.proxyService.put('TestCode/UpsertTestCode', testId));
- }
- getTestCode(testId: number): Observable<any> {
- return Observable.fromPromise(this.proxyService.get(TestCode/GetTestCodeById?testId=' + testId));
- }
- }
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.

Santosh Kumar AdidawarpuPosted Jan 18, 2018, 12:54 AM
Very good stuff, really I love it..
Swati TPosted Jan 17, 2018, 1:30 AM
Very very nice article.. Keep it up Santosh..