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 {}
  • 相关阅读:
    flume和kafka整合(转)
    Flume目录
    Flume的安装配置
    HBase系统架构及数据结构(转)
    toolbar ,textfield,图片拉伸,Bundle
    poj 1017 Packets
    jQuery使用serialize(),serializeArray()方法取得表单数据+字符串和对象类型两种表单提交的方法
    Android数据加密概述及多种加密方式 聊天记录及账户加密 提供高质量的数据保护
    LintCode-落单的数 III
    LeetCode90:Subsets II
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7277656.html
Copyright © 2011-2022 走看看