How To Set Authorization Headers in GET/POST Requests?

What Is HttpInterceptor in Angular?

The Http Interceptor is an interface and used to implement the intercept method.

Example -
//Register an Interceptor (HTTP_INTERCEPTORS) in the app Module.
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

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


And
//The HttpInterceptor is an interface and used to implement the intercept method.
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const reqHeader = req.clone({headers: req.headers.set('Authorization', 'MyAuthToken')});
    return next.handle(reqHeader);
  }
}



I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

What Is HttpInterceptor in Angular? What Is HttpInterceptor in Angular? Reviewed by Anil Singh on 2:09 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^