将环境变量传递给角度库 [英] Passing environment variables to angular library

查看:31
本文介绍了将环境变量传递给角度库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 angualr2-library yeoman 生成器创建了公司内部库.

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

一些 Angular 服务在我们当前的应用程序中使用环境变量(api 端点在每个 env 上都发生了变化).我想知道将当前环境对象传递给 angular2 库服务的最佳方法是什么?

Some of the angular services are using environment variables in our current applications (api endpoints are changed on each env). I was wondering what is the best way to pass the current environment object to the angular2 library services?

推荐答案

如果您仍在寻找解决方案,这里是我如何完成与您所要求的类似的事情(使用 Angular 4.2.4).

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).

在您的 AppModule(或您要导入库的位置)中,调用 LibraryModule 上的 forRoot() 方法.借助此功能,您可以将任何配置值传递给您的库,例如您应用的环境.

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 {
}

<小时>

LibraryModule当然需要提供forRoot()方法.在 providers 数组中,您可以提供服务、值等等.在这种情况下,为简单起见,'env' 充当持有给定环境对象的令牌.您也可以使用 InjectionToken 代替.


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
                }
            ]
        };
    }
}

由于令牌 env 现在由您的 LibraryModule 提供,您可以将其注入到其所有子服务或组件中.

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());
    }

}

希望能帮到你!

这篇关于将环境变量传递给角度库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆