将环境变量传递到angular2库 [英] passing environment variables to angular2 library

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

问题描述

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

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

一些角度服务在我们当前的应用程序中正在使用环境变量(每个环境中的api端点都已更改).我想知道将当前环境对象传递给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());
    }

}

希望对您有帮助!

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

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