Angular 4.3 Interceptors - How to use?

I am creating a new application that requires permission headers. I usually use something very similar to the approach found in this scotch.io article . But it occurred to me that HTTP interceptors are now fully supported in the Angular 4 ecosystem through the new HttpClientModule, and I'm trying to find documentation on exactly how to use them.

If I am wrong (starting from 4.3), it will be best practice to enter authorization headers, I will also be open to suggestions. I thought this was an added feature recently, which means there is probably good reason to switch to the Angular Approved method.

+6
source share
2 answers

This answer is borrowed from official documentation related to CodeWarrior.

Angular allows you to create an HttpInterceptor:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}

which can then be integrated into your application:

import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: NoopInterceptor,
    multi: true,
  }],
})
export class AppModule {}

To add an authorization header, you can clone the request with the modified headers:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const authHeader = this.auth.getAuthorizationHeader();
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
  }
}

Note that interceptors act as a chain, so you can configure multiple interceptors to perform various tasks.

+6
source

Including AuthService in the Interceptor constructor gave me this error:

Unprepared error: provider parsing errors: it is not possible to create a circular dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR →]"): in NgModule AppModule at. / Appmodule @ -1: -1

, , Injector of @angular/core, . localStorage auth.

Authorization: 'Bearer token_string'

:

token.interceptor.ts

import {Injectable, Injector} from '@angular/core';

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(private injector: Injector) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const auth = this.injector.get(AuthService);
        if (auth.getToken()) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${auth.getToken()}`
                }
            });

        }

        return next.handle(request);
    }
}

getToken AuthService

, . , , , JWT.

/**
 * Get jwt token
 * @returns {string}
 */
getToken(): string {
    return localStorage.getItem('token');
}

app.module.ts

TokenInterceptor

import {TokenInterceptor} from './pathToTheFile/token.interceptor';

@NgModule providers:.

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptor,
        multi: true
    }
    //, other providers
]
0

All Articles