import { Injectable } from '@angular/core' ; import { HttpRequest , HttpResponse , HttpHandler , HttpEvent , HttpInterceptor , HTTP_INTERCEPTORS } from '@angular/common/http' ; import { Observable } from 'rxjs/Observable' ; import 'rxjs/add/observable/of' ; import 'rxjs/add/observable/throw' ; import 'rxjs/add/operator/delay' ; import 'rxjs/add/operator/mergeMap' ; import 'rxjs/add/operator/materialize' ; import 'rxjs/add/operator/dematerialize' ; @ Injectable ( ) export class FakeBackendInterceptor implements HttpInterceptor { constructor ( ) { } intercept ( request , next ) { let testUser = { id : 1 , username : 'test' , password : 'test' , firstName : 'Test' , lastName : 'User' } ; return Observable . of ( null ) . mergeMap ( ( ) => { if ( request . url . endsWith ( '/api/authenticate' ) && request . method === 'POST' ) { if ( request . body . username === testUser . username && request . body . password === testUser . password ) { return Observable . of ( new HttpResponse ( { status : 200 , body : { token : 'fake-jwt-token' } } ) ) ; } else { return Observable . throw ( 'Username or password is incorrect' ) ; } } if ( request . url . endsWith ( '/api/users' ) && request . method === 'GET' ) { if ( request . headers . get ( 'Authorization' ) === 'Bearer fake-jwt-token' ) { return Observable . of ( new HttpResponse ( { status : 200 , body : [ testUser ] } ) ) ; } else { return Observable . throw ( 'Unauthorised' ) ; } } return next . handle ( request ) ; } ) . materialize ( ) . delay ( 500 ) . dematerialize ( ) ; } } export let fakeBackendProvider = { provide : HTTP_INTERCEPTORS , useClass : FakeBackendInterceptor , multi : true } ;