import { Injectable } from '@angular/core'; import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; let users = JSON.parse(localStorage.getItem('users')) || []; @Injectable() export class FakeBackend implements HttpInterceptor { intercept(request: HttpRequest, next: HttpHandler): Observable> { const { url, method, headers, body } = request; return of(null) .pipe(mergeMap(handleRoute)) .pipe(materialize()) .pipe(delay(500)) .pipe(dematerialize()); function handleRoute() { switch (true) { case url.endsWith('fake_login') && method === 'POST': return authenticate(); case url.endsWith('fake_registration') && method === 'POST': return register(); default: return next.handle(request); } } function authenticate() { const { username, password } = body; const user = users.find(x => x.username === username.value && x.password === password.value); if (!user) { console.log(password); return error('Username or password is incorrect.'); } return ok({ id: user.id, username: user.username, token: 'fake-jwt-token', }); } function register() { const user = body; if (users.find(x => x.username === user.username)) { return error('Username ' + user.username + ' is already taken.'); } user.id = users.length ? Math.max(...users.map(x => x.id)) + 1 : 1; users.push(user); localStorage.setItem('users', JSON.stringify(users)); console.log('Register user: ' + user); return ok(); } function ok(body?) { return of(new HttpResponse({ status: 200, body })); } function error(message) { return throwError({ error: { message } }); } } } export const fakeBackendProvider = { provide: HTTP_INTERCEPTORS, useClass: FakeBackend, multi: true, }