ben tedder : code things

Appending headers in Angular 4.3

I realize this post will quickly be out of date, but if you're having issues trying to figure out the new HttpClientModule or any of the new-ish Angular 4 http client stuff, hopefully this helps. I'm fairly sure this is useless information if you're already on Angular 5. But I've had packaging issues with 5, so I'm stuck w/4 for the time being.

Create an interceptor for your requests

An interceptor takes every request (or response) and modifies it as it goes out the door or comes back. For this blog post I'm just going to cover modifying your requests to add headers.

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

export class AppInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request.headers.append('Mycustomheader', 'some string');
    return next.handle(request);

Returning the next object feels eerily like Express, right? Interesting.

Link the interceptor in your main module

In your main @NgModule, create a new provider block like this:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppInterceptor } from './app-interceptor';

  providers: [
      provide: HTTP_INTERCEPTORS,
      useClass: AppInterceptor,
      multi: true

That's it!

It's pretty simple once you do it out. Previously I had used the 'merge' method of the BaseRequestOptions class, which used the RequestOptionsArgs and the RequestOptions, both of which did not use the new HttpHeaders, but the old Headers class.

Hope that helps!