passing environment variables to angular2 library

前端 未结 5 1840
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:13

    If You are still looking for the answer. In the current version i.e. Angular > 6, you don't have to do anything.

    The angular-cli commands "ng build --prod (for Production)& ng build (for Development)" will take care of it for you.

    Example: If you are running the project in development environment, all the variables are captured from src/environments/environment.ts. In your component library project just import "import { environment } from 'environments/environment';" (please make sure about the path) will takecare of the environment depending upon the angular-cli build command.

    0 讨论(0)
  • 2020-12-08 03:18

    I found an alternative solution to this problem in a GitHub issue. The solution in the GitHub thread has a bug (a typo), so I'm including the fixed solution here:

    To begin, add a provider to your top-level AppModule that contains your environment file.

    import {environment} from '../environments/environment'
    
    @NgModule({
      providers: [
        {provide: 'environment', useValue: environment}
      ]
      // object properties omitted for brevity...
    })
    class AppModule {}
    

    Finally, make use of an Inject decorator to include your environment file in any other part of your application you wish (library or otherwise):

    @Component({
      // object properties omitted for brevity
    })
    class MyComponent {
    
      private environment
    
      constructor(
        @Inject('environment')
        environment
      ) {
        this.environment = environment
      }
    
    }
    
    0 讨论(0)
  • 2020-12-08 03:19

    If you're trying to pass the environment variable for firebase, simply use this in your library:

    @NgModule({
      declarations: [MyAngularComponent],
      exports: [MyAngularComponent],
      imports: [
        AngularFireModule,
        AngularFirestoreModule,
        CommonModule
      ]
    })
    export class MyAngularModule {
    
      public static forRoot(firebaseConfig: FirebaseOptions): ModuleWithProviders<MyAngularModule> {
    
        return {
          ngModule: MyAngularModule,
          providers: [
            { provide: FIREBASE_OPTIONS, useValue: firebaseConfig }
          ]
        }
      }
    }
    

    And import it just like AngularFire...

    MyAngularModule.forRoot(environment.firebase)
    

    From this post: pass angularFire config imported in library using forRoot

    0 讨论(0)
  • 2020-12-08 03:29

    In case you still searching for a solution, here's how I accomplished something simliar to what you were asking for (using Angular 4.2.4).

    In your AppModule (or the place where you want to import your library), call the forRoot() method on your LibraryModule. With the help of this function, you can pass any config values to you library, e.g. your app's environment.

    import {environment} from "../environments/environment";
    ...
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            ...
            LibraryModule.forRoot(environment)
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

    You LibraryModule of course needs to offer the forRoot() method. In the providers array you then can provide services, values and more. In this case, 'env' acts as the token holding the given environment object for simplicity. You can also use an InjectionToken instead.

    @NgModule({
        ...
    })
    export class LibraryModule {
    
        public static forRoot(environment: any): ModuleWithProviders {
    
            return {
                ngModule: LibraryModule,
                providers: [
                    ImageService,
                    {
                        provide: 'env', // you can also use InjectionToken
                        useValue: environment
                    }
                ]
            };
        }
    }
    

    Since the token env is now provided by your LibraryModule, you can inject it in all of its child services or components.

    @Injectable()
    export class ImageService {
    
        constructor(private http: Http, @Inject('env') private env) {
        }
    
        load(): Observable<any> {
            // assume apiUrl exists in you app's environment:
            return this.http.get(`${this.env.apiUrl}/images`)
                .map(res => res.json());
        }
    
    }
    

    I hope that helps!

    0 讨论(0)
  • 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! ^_^

    0 讨论(0)
提交回复
热议问题