• [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 {}
  • 相关阅读:
    由大见小,从治国看企业管理,宜王霸之道
    止语
    VSTS团队浏览器文档相关
    《宇宙浪子》荐
    从《心物一元》到《神无方易无体》
    [导入][Tricks]在线字体测试
    [导入][Internet]Cheat Sheet: Web 2.0
    [导入][Code]Asp.net CSS问题
    一个JSON 实例 jQuery 解析JSON数据
    JQuery ajax 返回值如何进行赋值
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7277656.html
Copyright © 2020-2023  润新知