I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app.module, resulting in data being fetched from a JSON file instead of an external API. I found inspiration from this example: https://stackblitz.com/edit/angular-mock-http-interceptor For some reason, after implementing the interceptor, the subscription between my component and the data service seems to be broken. Despite building the same array structure for both the live and mock services, I cannot pinpoint why it's causing an issue. Here are the getter method and Observable from the service:
getUsers() {
this.http.get<any>('https://jsonplaceholder.typicode.com/users')
.subscribe(fetchedUsers => {
this.users = fetchedUsers;
this.usersUpdated.next([...this.users]);
});
}
getUsersUpdatedListener() {
return this.usersUpdated.asObservable();
}
The component that interacts with the service:
ngOnInit() {
this.usersService.getUsers();
this.usersSub = this.usersService.getUsersUpdatedListener()
.subscribe((users: User[]) => {
this.users = users;
});
}
And here is the code snippet for the interceptor class:
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import * as users from '../../assets/mockData/users.json';
const urls = [
{
url: 'https://jsonplaceholder.typicode.com/users',
json: users
}
];
@Injectable()
export class HttpMockRequestInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
for (const element of urls) {
if (request.url === element.url) {
console.log('Loaded from json : ' + request.url);
return of(new HttpResponse({ status: 200, body: ((element.json) as any).default }));
}
}
console.log('Loaded from http call :' + request.url);
return next.handle(request);
}
}
You can access the entire project on GitHub: https://github.com/reynoldsblair/learn-http
Could you help me understand why the interceptor is causing issues within my project?