passing environment variables to angular2 library

前端 未结 5 1855
Happy的楠姐
Happy的楠姐 2020-12-08 03:04

I\'ve created company internal library using angualr2-library yeoman generator.

Some of the angular services are using environment variables in our current applicati

5条回答
  •  醉话见心
    2020-12-08 03:31

    There is a Better Way I Think from here

    I thought you guys would find this useful: Using Abstract Classes As Dependency-Injection Tokens For Swappable Behaviors

    I have 3 Angular apps in an Nx project that share some common environment variables. A public site, a private portal, and an admin app. In my libs, I am using an abstract Environment class that defines common environment variables.

    export abstract class Environment {
      abstract readonly production: boolean;
      abstract readonly appUrls: {
        readonly public: string;
        readonly portal: string;
        readonly admin: string;
      };
    }
    

    Then I changed the 3 environment.ts files to be as follows.

    import { Environment } from '@my-lib-prefix/common';
    
    class EnvironmentImpl implements Environment {
      production = false;
      appUrls = {
        public: 'http://localhost:4200',
        portal: 'http://localhost:4201',
        admin: 'http://localhost:4202'
      };
    }
    

    export const environment = new EnvironmentImpl(); The environment.prod.ts would of course be symmetric to the dev environment.ts. Then I provide the respective environment dependency, in the root app.module.ts for each of the Angular apps.

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppComponent } from './app.component';
    import { Environment } from '@my-lib-prefix/common';
    import { environment } from '../environments/environment';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule],
      providers: [{ provide: Environment, useValue: environment }],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Now any component can inject environment dependencies in a clean, and common manner.

    import { Component } from '@angular/core';
    import { Environment } from '@my-lib-prefix/common';
    
    @Component({
      selector: 'my-login',
      templateUrl: './my-login.component.html'
    })
    export class MyLoginComponent {
      constructor(private env: Environment) {}
    }
    

    It enforces each environment.ts to implement the "common" environment variables defined in the abstract class. Also, each respective EnvironmentImpl can be extended with their own specific environment variables specific to the app. This approach seems very flexible and clean. Cheers! ^_^

提交回复
热议问题