I created one service for handling all http request. It is working perfectly. But I want to know is there any fault in my approach and also want to know other good approaches like observable?
request.service.js
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { MessageService } from './message.service'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }; interface IRequestOption { url: string; cxfgroup: string; endpoint: string; data: object; } interface IRequestBody { option: IRequestOption; log: string; error: string; } class HTTP { private messageService: MessageService; constructor(http, messageService, url: string, body: object, log: string, error: string) { this.callHTTP(http, url, body, log, error); this.messageService = messageService; } callHTTP(http, url, body, log, error) { return http.post(url, body, httpOptions).toPromise() .then(this.extractData) .catch(this.handleErrorPromise); } private extractData(res: Response) { // let body = res.json(); // return body['data'] || {}; return res || {}; } private handleErrorPromise(error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); } } class RequestFactory { private baseURL = 'https://app.domain.com/cxf/'; /** * CXF ENPOINTS */ private endpoints: any = { "auth": { "getcustomerkeys": "auth/getcustomerkeys" } }; call(http, messageService, options: IRequestOption, log: string, error: string) { let url: string = options.url ? options.url : this.baseURL; if (this.endpoints.hasOwnProperty(options['cxfgroup'])) { url += this.endpoints[options.cxfgroup][options.endpoint]; } return new HTTP(http, messageService, url, options.data, log, error); } } @Injectable() export class RequestService { constructor(private http: HttpClient, private messageService: MessageService) { } post(request: IRequestBody) { let requestFactory = new RequestFactory(); requestFactory.call(this.http, this.messageService, request.option, request.log, request.error); } } I'm calling this "post" method using the following code. Here I want to set a promise once the request complete i want to show some message.
this.requestService.post({ option: { url: '', cxfgroup: 'auth', endpoint: 'getcustomerkeys', data: { userid: '[email protected]' } }, log: 'login initiated!', error: 'customerKeyError' });