• [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 {}
  • 相关阅读:
    【JZOJ3347】树的难题
    【JZOJ3379】查询
    【JZOJ3337】wyl8899的TLE
    【JZOJ3318】Brunhilda的生日
    【JZOJ3319】雪地踪迹
    2018暑假集训——待做且可尝试去做的题
    2018暑假集训专题小结 Part.2
    2018.07.13【省赛模拟】模拟B组 【GDOI2016模拟】作业分配
    2018暑假集训专题小结 Part.1
    2018.07.12【2018提高组】模拟B组 【NOIP2015模拟10.27】魔法阵
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7277656.html
Copyright © 2020-2023  润新知