zoukankan      html  css  js  c++  java
  • [Angular] Intercept HTTP requests in Angular

    Being able to intercept HTTP requests is crucial in a real world application. Whether it is for error handling and logging or for injecting authentication tokens. While in Angular version 2 it intercepting HTTP requests was totally possible, implementing it wasn't that trivial and intuitive. Starting from Angular version 4.3.1 there is a new, way more simpler approach of implementing HTTP interceptors. In this lesson we're going to explore how.

    http.intercept.ts:

    import { Injectable } from '@angular/core';
    import {
      HttpInterceptor,
      HttpRequest,
      HttpResponse,
      HttpErrorResponse,
      HttpHandler,
      HttpEvent
    } from '@angular/common/http';
    
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    
    @Injectable()
    export class MyHttpLogInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('processing request', request);
    
        const customReq = request.clone({
          headers: request.headers.set('app-language', 'it')
        });
    
        return next
          .handle(customReq)
          .do((ev: HttpEvent<any>) => {
            if (ev instanceof HttpResponse) {
              console.log('processing response', ev);
            }
          })
          .catch(response => {
            if (response instanceof HttpErrorResponse) {
              console.log('Processing http error', response);
            }
    
            return Observable.throw(response);
          });
      }
    }

    Register:

    @NgModule({
      imports: [ BrowserModule, HttpClientModule ],
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: MyHttpLogInterceptor, multi: true }  
      ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}
  • 相关阅读:
    hibernate4.3.10使用注解映射方式样例
    eclipse ssh连接sqlserver express
    window2012 64bit 安装sqlserver2012 64bit调用excel的驱动安装
    SharpZipLib要支持unicode的文件名称
    搜索数据库中的内容
    AIX 添加开机启动项
    oracle 分区表和分区索引
    oracle 临时表学习
    oracle sys sysman system 介绍
    oracle to_date函数(转载)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7277656.html
Copyright © 2011-2022 走看看