Skip to main content
added 1634 characters in body
Source Link

HttpInterceptor will apply some middleware functionality to all HTTP calls made with HttpClient provider. Please note it won't work with Http provider as it's deprecated in the latest releases. And don't forget to include thisthe interceptor in @NgModule:

A similar approach can be used to inject Authorization token etc.

And don't forget to include this in @NgModule:

A similar approach can be used to inject Authorization token.

HttpInterceptor will apply some middleware functionality to all HTTP calls made with HttpClient provider. Please note it won't work with Http provider as it's deprecated in the latest releases. And don't forget to include the interceptor in @NgModule:

A similar approach can be used to inject Authorization token etc.

added 1634 characters in body
Source Link

Usage example in services

Usage example in components

Error Handling

To handle errors we can use HttpInterceptor so it's gonna look something like this:

import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS, } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { _throw } from 'rxjs/observable/throw'; import 'rxjs/add/operator/catch'; @Injectable() export class ErrorInterceptor implements HttpInterceptor { intercept( req: HttpRequest<any>, next: HttpHandler, ): Observable<HttpEvent<any>> { return next.handle(req).catch(errorReponse => { let error: string; if (errorReponse instanceof HttpErrorResponse) { error = errorReponse.error; const { status, statusText, message } = errorReponse; const errMsg = `HTTP ERROR: ${status} - ${statusText}\n${message}\n\nBACKEND RESPONSE: `; console.error(errMsg, error); } else { error = null; } return _throw(error); }); } } export const ErrorHttpInterceptor = { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true, }; 

And don't forget to include this in @NgModule:

@NgModule({ providers: [ErrorHttpInterceptor] }) 

A similar approach can be used to inject Authorization token.

Usage in services

Usage in components

Usage example in services

Usage example in components

Error Handling

To handle errors we can use HttpInterceptor so it's gonna look something like this:

import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS, } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { _throw } from 'rxjs/observable/throw'; import 'rxjs/add/operator/catch'; @Injectable() export class ErrorInterceptor implements HttpInterceptor { intercept( req: HttpRequest<any>, next: HttpHandler, ): Observable<HttpEvent<any>> { return next.handle(req).catch(errorReponse => { let error: string; if (errorReponse instanceof HttpErrorResponse) { error = errorReponse.error; const { status, statusText, message } = errorReponse; const errMsg = `HTTP ERROR: ${status} - ${statusText}\n${message}\n\nBACKEND RESPONSE: `; console.error(errMsg, error); } else { error = null; } return _throw(error); }); } } export const ErrorHttpInterceptor = { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true, }; 

And don't forget to include this in @NgModule:

@NgModule({ providers: [ErrorHttpInterceptor] }) 

A similar approach can be used to inject Authorization token.

Source Link

HTTP Service

Here is an observable based approach we're using in our projects:

import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class HttpService { constructor(private http: HttpClient) {} /** * Invoke function should be able to handle any HTTP request based on the @params */ invoke(params): Observable<any> { if (params) { const method = params.method.toLowerCase(); const { url, path, body, headers, query } = params; const requestURL = `${url}/${path}`; let request; let requestParams = new HttpParams(); let requestHeaders = new HttpHeaders(); /** * DEFAULT HEADERS */ requestHeaders = requestHeaders.set('Content-Type', 'application/json'); /** * CUSTOM HEADERS */ if (headers) { for (const key in headers) { if (headers.hasOwnProperty(key)) { requestHeaders = requestHeaders.append(key, headers[key]); } } } /** * CUSTOM REQUEST QUERY (?key=value) */ if (query) { for (const key in query) { if (query.hasOwnProperty(key)) { requestParams = requestParams.append(key, query[key]); } } } const requestOptions = { headers: requestHeaders, params: requestParams, }; /** * HANDLE GET, POST etc. REQUESTS */ if (method === 'get') { request = this.http[method](requestURL, requestOptions); } else if (method === 'post' || method === 'put') { request = this.http[method]( requestURL, JSON.stringify(body), requestOptions, ); } else if (method === 'delete') { request = this.http.request(method, requestURL, { ...requestOptions, body: JSON.stringify(body), }); } else { console.error('Unknown request method.'); } /** * RETURN API REQUEST */ return request; } } } 

Usage in services

Which is very simple to use in your service, so it's gonna look like this:

constructor(private http: HttpService) {} makeRequest() { return this.http.invoke({ method: 'POST', // method like POST, GET etc. url: 'http://blabla', // base URL path: 'makeReq', // API endpoint body: ..., // body for POST or PUT requests headers: {headerName: 'HeaderValue'} // headers you need to add to your request query: {query: 'queryValue'} // URL query to be added (eg. ?query=queryValue) }); } 

Please note that body, headers and query are optional.

Usage in components

And finally, you need to subscribe to an Observable in your components to make the request:

this.yourServiceName.makeRequest().subscribe( success => { // handle success }, error => { // handle error } );