[英]Angular CLI 6.x environment files for a library
I've created a library with the new CLI 6.x. 我用新的CLI 6.x创建了一个库。 I've also created an Angular service inside it and I would like to use different URLs for my dev and prod environment.
我也在其中创建了一个Angular服务,我想为我的dev和prod环境使用不同的URL。 So I created an
environment.ts
and an environment.prod.ts
file in my library folder. 所以我在我的库文件夹中创建了一个
environment.ts
和environment.prod.ts
文件。
//dev export const environment = { production: false, url: 'dev-url' }; //prod export const environment = { production: true, url: 'prod-url' };
I also added the 'fileReplacements' property to the angular.json
file: 我还将'fileReplacements'属性添加到
angular.json
文件中:
"configurations": { "production": { "fileReplacements": [{ "replace": "projects/tk-shared/src/environments/environment.ts", "with": "projects/tk-shared/src/environments/environment.prod.ts" }], "project": "projects/tk-shared/ng-package.prod.json" } }
Compiling the library with the ng build tk-shared
works and uses the dev
settings, however when compiling with ng build --prod tk-shared
I get the following error: 使用
ng build tk-shared
编译库并使用dev
设置,但是在使用ng build --prod tk-shared
编译时,我收到以下错误:
Schema validation failed with the following errors: Data path "" should NOT have additional properties(fileReplacements).
My tip is that the reason is that tk-shared
has the projectType: "library"
property in angular.json
. 我的技巧是,其原因在于
tk-shared
有projectType: "library"
物业angular.json
。
Anyway, is it possible to use environment files in a library? 无论如何,是否可以在库中使用环境文件?
Thanks, @R. 谢谢,@ R。 Richards for pointing me to the right solution!
理查兹指出我正确的解决方案! These two sources helped me figure out how to do this injection correctly: LINK1 and LINK2 .
这两个来源帮助我弄清楚如何正确地进行这种注射: LINK1和LINK2 。
So what I did ... 所以我做了什么......
Created an InjectionToken
and modified my TkSharedModule
: 创建了一个
InjectionToken
并修改了我的TkSharedModule
:
export const BASE_URL = new InjectionToken<string>('BASE_URL'); //... export class TkSharedModule { static forRoot(host: string) { return { ngModule: TkSharedModule, providers: [{ provide: BASE_URL, useValue: host }] } } }
Provided a value for this token from the environment
files in my AppModule
: 从
AppModule
的environment
文件中为此标记提供了一个值:
import {environment} from '../environments/environment'; //... @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, TkSharedModule.forRoot(environment.url) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
And finally injected this value in my service: 最后在我的服务中注入了这个值:
//MyServiceService import { BASE_URL } from '../tk-shared.module'; constructor(@Inject(BASE_URL) BASE_URL: string) { console.log('base url', BASE_URL); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.