0

I want to set header for all request. don't want to set header for each request again and again like i have code like this

public update(student: Student): Promise<Student>
{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('authentication', `${student.token}`);

    const url = `${this.studentsUrl}`;

    return this.http
        .put(url, JSON.stringify(student), { headers: headers })
        .toPromise()
        .then(() => student)
        .catch(this.handleError);
}

so is there any way from which i can set generic header for each request ?

user1608841
  • 2,455
  • 1
  • 27
  • 40
Fahad Subzwari
  • 2,109
  • 3
  • 24
  • 52

1 Answers1

1

UPDATE :

To add generic header below angular 4.3 you may need to develop custom service. Please refer this answer which explains best possible solution prior to angular 4.3.

Hi you can try HTTP interceptor:

Note : HTTP interceptors are supported by Angular 4.3+

This is interceptor file

import { Injectable, NgModule} from ‘@angular/core’;
import { Observable } from ‘rxjs/Observable’;
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’;
import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
@Injectable()
export class MyInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      const dupReq = req.clone({ headers: req.headers.set(‘Consumer-Secret’, ‘some sample key’) });
      return next.handle(dupReq);
   }
};

and in app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './interceptors/my.interceptor';


@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Please refer to this site for reference

user1608841
  • 2,455
  • 1
  • 27
  • 40