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 {}
  • 相关阅读:
    javaScript删除对象、数组中的null、undefined、空对象、空数组方法
    js数组方法 改变原数组和不改变原数组的方法整理
    js时间戳与日期格式的相互转换
    [原创]jquery更换头像
    css样式大全(copy自一个大佬的博文)
    【原创】实现点击按钮更换表格皮肤效果
    Cookie和Seesion
    常用正则表达式
    【原创】javaWeb完成增删查改功能
    javaWeb完成注册功能
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7277656.html
Copyright © 2011-2022 走看看