angular interceptors code example
Example 1: http interceptor angular
import { Injectable } from '@angular/core';
import decode from 'jwt-decode';
@Injectable()
export class AuthService {
public getToken(): string {
return localStorage.getItem('token');
}
public isAuthenticated(): boolean {
const token = this.getToken();
return tokenNotExpired(null, token);
}
}
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({ bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]})
export class AppModule {}
Example 2: interceptor in angular 8
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}
Example 3: angularjs interceptor
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
return config;
},
'requestError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
},
'response': function(response) {
}
};
});
Example 4: angular interceptor
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
]
})
export class AppModule {}
Example 5: interceptors
const api = axios.create({
baseURL: '/',
headers: {
'Content-Type': 'application/json'
},
})
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers['Authorization'] = `Token ${token}`
}
return config
},
error => Promise.reject(error)
)
export default api