Intercept all HTTP requests from angular2

Asked

Viewed 236 times

2

I’m looking for a way to intercept all HTTP requests from the angle and add a few headers. In versions prior to angular2 RC5 (before the NgModule) was that way, for example:

class MyOptions extends BaseRequestOptions {
    Authorization: string = 'Bearer ' + localStorage.getItem('tokenName');
}

bootstrap(AppComponent,
    [HTTP_PROVIDERS,
        { provide: RequestOptions, useClass: MyOptions },
    appRouterProviders,
    disableDeprecatedForms(),
    provideForms(),
]).catch(err => console.error(err));

I’m currently in the version 2.0 final and as per research on how this would be implemented in this version, would be something similar to this:

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  providers: [
    { provide: RequestOptions, useClass: MyOptions }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

@Injectable()
export class MyOptions extends RequestOptions {
  constructor() { super({method: RequestMethod.Get, headers: new Headers()}); }
}

which presents the following error:: TypeError: Cannot read property 'merge' of null. As can be seen in this example.

Note: The implementation of MyOptions is the same as BaseRequestOptions, I copied it so if you use BaseRequestOptions in { provide: RequestOptions, useClass: BaseRequestOptions}, everything works, as can be observed in this example.

1 answer

1


Create an interception class:

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

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            req = req.clone({
                headers: req.headers.set('NOME', 'VALOR') //setar os headers que você quer
            });
        return next.handle(req);
    }
}

And in app.module.ts, add the following object in Property providers:

{
   provide: HTTP_INTERCEPTORS,
   useClass: RequestInterceptor,
   multi: true
}

This way all the requests made will go through this third party.

Angular Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.