Angular 8 HTTP Interceptor causing issues with subscriptions

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?

Answer №1

Hey there, just wanted to let you know that your interceptor is working perfectly fine. The issue lies in your user-list.component.ts file. It seems that the subscription to

this.usersService.getUsersUpdatedListener()
is happening after this.usersService.getUsers();, which can lead to a race condition. To fix this, make sure to move the subscription logic above the call to getUsers. Once you do that, everything should work smoothly for both HttpRequestInterceptor and HttpMockRequestInterceptor.

 ngOnInit() {
    this.usersSub = this.usersService.getUsersUpdatedListener()
      .subscribe((users: User[]) => {
        this.users = users;
      });
    this.usersService.getUsers();
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing JSON data stored locally and initializing it into a TypeScript variable within a React application

I'm new to working with JSON arrays and I'm facing a challenge. I am looking for a way to load data from a JSON file into a Typescript variable so that I can perform a specific operation that involves arrays. However, I'm unsure of how to ac ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Is it possible to access your app directly from the browser without requiring any user prompts?

After successfully setting up my app for both android and ios with the necessary app link and universal link, I am now focusing on redirecting users from a specific website to my app. The mobile aspect is all set, but I need to work on the browser/server s ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

When attempting to import the image path from a JSON file, a ReferenceError occurs stating that the data variable is not

I'm currently attempting to iterate through image paths in a JSON file and display them in a browser using the "img" tag. While hardcoded values work perfectly fine, I encountered an issue when trying to switch to a variable as outlined in this post: ...

Issue with passing JSON object from Angular2 HTTP post to MVC 6 controller action

In my current project, I am developing an angular 2 application using asp.net MVC6. The issue I am facing is related to Angular2 Http post method calls in the controller action. It works perfectly fine when there are no parameters/properties involved. Howe ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

Stop material button from animating when clicked

On my webpage, I have created a unique button structure using Angular Material design: <button mat-button class="library-tile-button"> <button mat-button class="edit-library-button"> <img class="edit-library-img" src="..."/> ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...

Is it possible for Visual Studio Code to create type declarations?

One of my tricks for quickly obtaining typings involves deriving them from actual data: https://i.stack.imgur.com/EPtMm.png I typically use a snippet like this: const ParcelFeatureTypeInstance = {"displayFieldName":"NAMECO","fieldAliases":{"PIN":"PIN / ...

The Angular component seems to be lacking a template

During the upgrade process of my Angular 8 app to Angular 9, I encountered an error message while trying to build: ERROR in component is missing a template The issue is that it doesn't specify which specific component is missing a template. Is there ...

A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error: https://i.stack.imgur.com/zY1io.png Below is the code snippet for the AppModule: @Module({ imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:2 ...

Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask: public send_login(user){ console.log(user) return this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions) .pip ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

What Mac OSX command can you use in Typescript to input the quote character for multiline text?

Just starting out with Angular 2 and working through the official tutorial at https://angular.io/docs/ts/latest/tutorial/toh-pt1.html. I've realized that to use multi-line template strings (string interpolation), I have to use the ` mark. Any tips fo ...

An Unexpected ER_BAD_FIELD_ERROR in Loopback 4

I encountered an unusual error: Unhandled error in GET /managers: 500 Error: ER_BAD_FIELD_ERROR: Unknown column 'role_id' in 'field list' at Query.Sequence._packetToError (/Users/xxxx/node_modules/mysql/lib/protocol/se ...