Last updated on November 20, 2017
Using HTTP service directly in all over the application is not scalable, its only work for small applications. Having a central location to manage HTTP calls, will reduce the maintenance and its robust solution. We can inject this global service into any component.
Global API service request method
Lets create a new service called APIService, filename name is api.service.ts
, you can place this wherever you want in your application, preferred location is app\shared
. As I have copied directly from my project adjust your env config and rxjs dependencies as for your application setup.
Below is my complete working common api service request method.
import { Injectable } from '@angular/core'; import { Http, Headers, Request, RequestOptions, Response, RequestMethod } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { Config } from '../shared/config/env.config'; @Injectable() export class ApiService { private baseUrl = Config.API; constructor( private http: Http ) { } get(url: string) { return this.request(url, RequestMethod.Get); } post(url: string, body: object) { return this.request(url, RequestMethod.Post, body); } put(url: string, body: object) { return this.request(url, RequestMethod.Put, body); } delete(url: string) { return this.request(url, RequestMethod.Delete); } private request(url: string, method: RequestMethod, body?: object) { const headers = new Headers(); const token = localStorage.getItem('token'); if (token) { headers.append('Authorization', token); } headers.append('Accept', 'application/json'); headers.append('Content-Type', 'application/json'); const reqeustOptions = new RequestOptions({ url: `${this.baseUrl}/${url}`, method: method, headers: headers }); if (body) { reqeustOptions.body = body; } const request = new Request(reqeustOptions); return this.http.request(request) .map((res: Response) => res.json()) .catch(this.handleError); } private handleError(error: Response) { return Observable.throw(error.json()); } }
Now add this to app module providers array
providers: [ApiService]
How to use common service method
Just like any other class, import APIService into current locations, for example, I want to use it inside my change password service(changepassword.service.ts
), the code should be something like shown below
import { Injectable } from '@angular/core'; import { ApiService } from '../../shared/api.service'; // adjust this path as for your project structure @Injectable() export class ChangePasswordService { constructor(private apiService: ApiService) { } changePassword(data: object) { return this.apiService.post(`change-password`, data); } }