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

Exploring the Integration of Angular 5 with Firestore for Working with Nested

I have a firestorm collection that follows this specific structure: USERID { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="354150464175415046411b565a58">[email protected]</a>" name: "John Doe" ...

Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me: this.dropDownFilter = values => values.filter(option => option.value ...

I am having trouble viewing the input value on my Angular5 form

Here is the HTML code snippet that I've written: <input type="text" name="fechainscripcion" #fechainscripcion="ngModel" [(ngModel)]="alumno.fechainscripcion" value="{{today | date:'dd/MM/yyyy'}}" class="form-control" /> This is a seg ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

How can I pass Checkbox values to a function in the component in Angular 2?

Hello, I am new to Angular and currently working with NgFor. I have a requirement where I need to display elements that can be selected by the user. Upon selection, I should be able to retrieve the ID in the Component function. However, when I tried usin ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

"Encountering an issue where attempting to set a property on an undefined variable, despite it being

I've been working on a timer app/component, but I'm running into an issue. The error message reads: Cannot set property startAt of undefined. I've defined it in my dashboard component, so I'm not sure where the problem lies. Any suggest ...

Angular2 module encounters failure when trying to inject InjectionToken using @Inject()

I've recently encountered an issue with InjectionToken that is declared within a module. import {InjectionToken, NgModule} from '@angular/core'; import {SampleComponent} from './sample.component'; export let SOME_TOKEN = new Inje ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Using Angular and RxJS5 to refresh data from both HTTP requests and sockets

Here's a specific scenario I need to address: Retrieve route parameters Utilize route parameters to make an HTTP service call Upon receiving a response from the HTTP service, use the same route parameters to invoke a socket service Whenever the sock ...

What is causing the issue with entering the code? Exploring the restrictions of the mui tag

Can someone explain why I am unable to use boolean data type in this code snippet? I am trying to determine whether the user is an admin or not, and based on that, hide or disable a button. const Authenticate = useSelector(userSelector) let checkValue ...

The name is not found when using attribute, but it is found when using extends

Lately, I've encountered difficulties with creating large TypeScript modules, and there's one thing that has been puzzling me. Specifically, the following scenario doesn't seem to work: // file A.ts export = class A { } // file main.ts imp ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role. Here is my current approach: <form [formGroup]="rolesForm"> <label formArrayName="roles" *ngFor=" ...

Tips for selecting objects based on property in Typescript?

Consider this scenario: import { Action, AnyAction } from 'redux'; // interface Action<Type> { type: Type } and type AnyAction = Action<any> export type FilterActionByType< A extends AnyAction, ActionType extends string > ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Typedoc does not create documentation for modules that are imported

Whenever I generate documentation with TypeDoc, I am encountering an issue where imported files come up empty. If I add a class to the file specified in entryPoints, I get documentation for that specific class. However, the imported files show no document ...

Unable to execute karma test cases as a result of ngOnDestroy being inaccessible

I have a component structured as follows: export class InkbarComponent implements AfterViewInit, OnDestroy { resizeListener: any; constructor(private _renderer: Renderer, private _elementRef: ElementRef, public renderer: Renderer) { } ngAfter ...