Unused Angular conditional provider found in final production bundle

Looking for a way to dynamically replace a service with a mock service based on an environment variable? I've been using the ?-operator in the provider section of my module like this:

@NgModule({
  imports: [
    ...
  ],
  providers: [
    ...
    environment.e2e ? { provide: MyService, useClass: MyServiceMock} : MyService
  ],
})
export class DemoModule {
}

While this method functions as intended - switching between the mock and real service based on the 'e2e' variable - it does come with a downside. When building in production mode (with e2e=false), the code for the mock service still gets included in the compiled bundle. I also attempted to replace the Service using a factory within the @Injectable decorator. Although this approach correctly swaps out the service, the mock service ends up in the production bundle once again.

@Injectable({
  providedIn: 'root',
  useFactory: (dep1, dep2) => environment.e2e ? new MyServiceMock(dep1, dep2) : new MyService(dep1, dep2),
  deps: [dep1, dep2]
})
export class MyService {
...
}

Does anyone have insights on how to replace a service based on the environment without including the mock service in the production bundle?

Answer №1

It seems like the issue is related to initializing a runtime build variable. If you update environment.e2e to its final value, such as true or false, the behavior should be as expected.

To avoid unnecessary code in the final bundle, I discovered a single solution: modifying the build configurations in the angular.json file. By performing file replacements here, you can achieve the desired outcome:

"fileReplacements": [
  {
    "replace": "src/app/services/my-service.service.ts",
    "with": "src/app/services/mocks/my-service-mock.service.ts"
  },
  ...
],

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

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

Steps for setting up multiple tables in an Ionic Angular app using SQLITE

Attempting to create multiple tables in SQLITE within an Ionic project, I've encountered issues with the current format. Can anyone suggest a solution or method for creating multiple tables in SQLITE within an Ionic project? Thank you in advance. fun ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

Passing information from a provider to a page in Ionic2

I am currently diving into the world of Angular2 and I'm striving to comprehend the process of data passing from a provider to a specific page. Within the pages directory, there exists a subdirectory named job-match, where the file job-match.js resid ...

Firebase/Angular: authentication user not detected

After going through all the discussions on this issue, I am still unable to implement the solutions in my setup. In my Firebase database, I have the following nodes: I have connected a service to a simple reactive form for user registration: export class ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Support for ViewEncapsulation.ShadowDom now available in Edge, Internet Explorer, and legacy browsers

I am working with Angular 7 and material design. Some of my components utilize ShadowDOM ViewEncapsulation, leading to errors in older versions of IE, Edge, Chrome, and Firefox. Below is the error message I am encountering: Object doesn't support pr ...

Prisma: Incorrectly identifying existing items where the list contains any of the specified items

Within my Prisma model, I have a property designated to store a list of phone numbers in the format phones String[] @unique When making an API call with a model that may include one or more phone numbers, my goal is to locate any existing record where any ...

Integrity parameter in Angular2+ is utilized for ensuring the integrity of a local script file

I have encountered an issue with my AngularJS project. I have 2 scripts located in the asset folder and I generated integrity hashes for them using . While everything works fine on my localhost, when I upload it to the server, only Internet Explorer seems ...

The Angular Ngrx store function, store.select('selector name'), should ideally provide a list of Books but instead, it is returning a non-iterable list

Can someone help me troubleshoot this issue? It's my first time using state management. The result I get when trying to fetch it from the state is not what I expected. Here is the reducer: import {createReducer, on} from '@ngrx/store'; imp ...

Users are reporting a problem with the PrimeNG confirmation dialog where it becomes unresponsive and locks up the screen

Previously functioning code seems to have been affected by an update to PrimeNG. The confirmation dialog that was once usable is now hidden behind a gray click-mask, rendering everything on the screen unclickable: The HTML structure for these two dialogs ...

Tips for preventing words from being split between lines in an error message

I am encountering a problem in Angular 2 where error messages are being split onto two lines when there isn't enough space for the entire word. Check out this screenshot for reference Is it possible to prevent words from being divided across lines? ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

Is there a way to showcase just the month in one spot when presenting data using Angular 13?

Just starting out with Angular and facing a challenge in the Milestone section. There is a loop for displaying years and months, but I need to ensure that the month name is displayed only once for each specific year. Can someone provide me with a possible ...

Changing the size of a div component using Angular 6

Currently, I am working on implementing Angular's element resize feature. I am utilizing this library: https://github.com/mattlewis92/angular-resizable-element Here is my custom module: import { ResizableModule } from 'angular-resizable-elemen ...

The reason behind the ghost problem - classRef isn't recognized as a constructor

Recently, I encountered an issue where the app was not loading in the browser while running an Angular NX project locally with the command "start-dev": "nx run-many --target=serve --all". The screen would get stuck on our loading animat ...