http interceptor angular 8

Solutions on MaxInterview for http interceptor angular 8 by the best coders in the world

showing results for - "http interceptor angular 8"
Lilly
20 Jan 2018
1import { Injectable } from '@angular/core';
2import { HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler } from '@angular/common/http';
3import { Observable } from 'rxjs';
4
5@Injectable()
6export class MyInterceptor implements HttpInterceptor {
7  intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
8    return next.handle(httpRequest);
9  }
10}
11
Louis
29 Jul 2018
1// src/app/auth/auth.service.ts
2
3import { Injectable } from '@angular/core';
4import decode from 'jwt-decode';
5
6@Injectable()
7export class AuthService {  
8  public getToken(): string {
9    return localStorage.getItem('token');
10  }  
11
12	public isAuthenticated(): boolean {    
13      // get the token
14      const token = this.getToken();    
15      // return a boolean reflecting 
16      // whether or not the token is expired
17      return tokenNotExpired(null, token);  
18    }
19}
20
21// src/app/auth/token.interceptor.ts
22import { Injectable } from '@angular/core';
23import {
24  HttpRequest,
25  HttpHandler,
26  HttpEvent,
27  HttpInterceptor
28} from '@angular/common/http';
29import { AuthService } from './auth/auth.service';
30import { Observable } from 'rxjs/Observable';
31@Injectable()
32export class TokenInterceptor implements HttpInterceptor {
33  constructor(public auth: AuthService) {}
34  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
35    
36    request = request.clone({
37      setHeaders: {
38        Authorization: `Bearer ${this.auth.getToken()}`
39      }
40    });
41    return next.handle(request);
42  }
43}
44
45// src/app/app.module.ts
46import { HTTP_INTERCEPTORS } from '@angular/common/http';
47import { TokenInterceptor } from './../auth/token.interceptor';
48
49@NgModule({  bootstrap: [AppComponent],
50          	 imports: [...],
51			 providers: [
52                       { 
53                       provide: HTTP_INTERCEPTORS,
54                       useClass: TokenInterceptor,
55                       multi: true   
56                       }  
57          ]})
58export class AppModule {}