Utilize environment.ts in Angular library module for importation purposes

I have an angular monorepo and I'm looking to reuse a specific module across multiple projects without duplicating it. The challenge is to use the environment specific to each project, rather than copying and pasting the code into each one.

import { environment } from '../environments/environment';

@NgModule({
  imports: [
    provideFirebaseApp(() => initializeApp(environment.firebaseConfig))
  ]
})
export class AngularFirebaseV7Module { }

This module utilizes the new API for angular firebase version 7, which is explained here.

To achieve this, I'm attempting to integrate this into a library.

Referring to Pass environment.ts To Angular Library Module, it seems that I can pass the environment as configuration and inject it using:

AngularFirebaseV7Module.forRoot(environment.firebaseConfig)
import { InjectionToken, ModuleWithProviders, NgModule } from '@angular/core';

import { initializeApp, provideFirebaseApp } from '@angular/fire/app';


// Here's what I want to eliminate:
import { environment } from '../environments/environment';

interface IFirebaseConfig {
    apiKey: string
    authDomain: string
    projectId: string
    storageBucket: string
    messagingSenderId: string
    appId: string
    measurementId: string
}

export const FIREBASE_CONFIG = new InjectionToken<IFirebaseConfig>('FIREBASE_CONFIG');

@NgModule({
  declarations: [],
  imports: [
    provideFirebaseApp(() => {
      // I want to avoid using `environment.firebaseConfig` directly but instead use the config passed in
      return initializeApp(environment.firebaseConfig)
    })
  ]
})
export class AngularFirebaseV7Module {

  static forRoot(config: IFirebaseConfig): ModuleWithProviders<AngularFirebaseV7Module> {

    // Access to the config is available here but not for imports
    console.log(config)

    return {
      ngModule: AngularFirebaseV7Module,
      providers: [
        {
          provide:  FIREBASE_CONFIG,
          useValue: config
        }
      ]
    };
  }

}

However, how can I utilize this config within the imports like

provideFirebaseApp(() => initializeApp(config))
?

Answer №1

The function <strong>provideFirebaseApp</strong> accepts a callback as an argument, and that callback will receive an instance of the <strong>Injector</strong>.

export function provideFirebaseApp(fn: (injector: Injector) => IFirebaseApp, ...deps: any[]): ModuleWithProviders<FirebaseAppModule> {
  return {
    ...
  };
}

Link to source code

Using the injector, you can retrieve your configuration like this:

provideFirebaseApp((injector) => {
  return initializeApp(injector.get(FIREBASE_CONFIG))
}),

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

Restoring ngModel value in Angular's input field back to its original state

Currently, I am utilizing Angular 10 in conjunction with Nebular 6. My goal is to implement the following: Within a form, there exist two input date fields, labeled as start of project and end of project. Should a user attempt to input an invalid date (u ...

Absence of "Go to Definition" option in the VSCode menu

I'm currently working on a Typescript/Javascript project in VSCODE. Previously, I could hover my mouse over a method to see its function definition and use `cmd + click` to go to the definition. However, for some unknown reason, the "Go to Definition" ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Using textContent as an input attribute in Angular results in an error

One of my recent projects involved creating a directive wrapper for strokeText.js, which allows for text to have an outline added to it using the canvas api. In some instances, I needed to apply this effect to dynamic text that changes based on user input. ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Utilize SCSS function by passing in variable parameters

Currently, I am utilizing Angular and SCSS for my style needs. In SCSS, I have the ability to declare variables and reuse them later on. For instance: $color-accent: #30bdff; $color-accentLight: mix(white, $color-accent, 90%); However, what happens if a u ...

What's up with the strange event handling in Angular2?

How can a draggable vertical bar be created with Angular2? Setting isDragging to true when the user clicks it and calling moveHandler when the mouse moves seems straightforward, but there are a couple of issues: When the if-condition in ngOnInit is true, ...

Display responsive input field based on selected option in ionic2 dropdown menu

When the user selects 'Other' from the dropdown menu using Ionic2 and Angular2, I want to provide them with an option to enter their profession. Here is a visual representation of the select box: https://i.sstatic.net/CRjAl.png Below is the co ...

Is there a way to determine the height of the ion-footer?

Is there a way to obtain the height of the ion-footer element in Ionic2? I want to calculate the initial window height minus the ion-footer height, but I am currently only able to get the overall window height. I'm not interested in retrieving the ...

initiating nest start removes the json files in the dist directory

As I work on my nestjs application, I find myself needing to ensure that specific json files are copied to the dist directory. This is especially important for the "engines" folder, where the json files in src/engines must be replicated in dist/and prod. ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...

Establish a connection using Angular 4 HTTP POST to communicate with a Java REST API, as it is not permitted on the server

I am facing an issue with my Angular 4 client service that is calling a REST method declared on a Java server using a PostMapping annotation. When I make the call from Angular, it is not accepted by the server. However, when testing it on Postman, it work ...

Can someone explain how to implement document.querySelector in TypeScript within the Angular framework?

I am tackling the task of creating a login/register form that allows users to switch between the two forms with the click of a button. The goal is to only display one form at a time. Initially, I implemented this functionality in a basic HTML file and it w ...

In Typescript, you can extend an interface with the Node type to specifically

I'm currently utilizing Cypress 10. I came across the following code snippet: Cypress.Commands.add( 'byTestId', // Taking the signature from cy.get <E extends Node = HTMLElement>( id: string, options?: Partial< ...

Passing additional parameters to an Angular directive individually

Is there a way to pass two parameters separately to my directive instead of as one combined parameter? Currently, I am able to add the parameters as one parameter (*ovLoading="!isDataReceived;noBackground:true"), but I would prefer to have them as two sepa ...

What steps can be taken to initiate Nx Release on the apps/* when modifications are made to the connected libs/* modules?

Trying out the nx release command but struggling to get it to release an app when there are changes to a dependent module. Examining the graph below, you can see that I have 3 apps, with 2 depending on the shared-ui module. https://i.sstatic.net/QYDBlRnZ.p ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...