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) {
- }
-
-
-
-
-
-
- get(uri: string | Request): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Get, uri));
- }
-
-
-
-
-
-
- delete(uri: string | Request): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Delete, uri));
- }
-
-
-
-
-
-
-
- post(uri: string | Request, body: any): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Post, uri, body));
- }
-
-
-
-
-
-
-
- put(uri: string | Request, body: any): Promise<any> {
- return this.request(this.newRequest(RequestMethod.Put, uri, body));
- }
-
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
-
-
- 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);
- }
-
-
-
-
-
-
- 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) { }
-
- 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.