构建后配置角度生产文件 [英] Configuring angular production files after build
问题描述
我有一个 angular 9 项目,它是应用程序套件安装程序 [Wix 安装程序] 的一部分.angular 应用程序使用的设置之一是 API 的地址,它从某个可配置的地址获取数据.我知道我可以有很多 angular 环境文件,只需使用如下命令:
I have an angular 9 project which is part of an application suite installer [Wix installer]. One of the settings used by the angular app is the address of API which it fetches its data from some configurable address. I know that I can have many angular environment files and simply use commands such as the followings:
environment.env1.ts
export const environment = {
production: true,
apiAddress: "http://apiAddress1/api/",
};
ng build --prod --configuration=env1
或
environment.env2.ts
export const environment = {
production: true,
apiAddress: "http://apiAddress2/api/",
};
ng build --prod --configuration=env2
这意味着对于每个潜在的 API 地址,我都需要进行新的构建并运行上面的命令.如何克服上述情况并在构建后配置输出二进制文件?
This means for every potential API address I need to do a new build and run above command. How can I overcome above scenario and configure output binaries after the build?
假设没有明确的方式实现after-built配置,我可以对生成的main*.js文件中的API地址做简单字符串替换"吗?会不会有副作用?
Assuming there is no clear way of achieving the after-built configuration, can I do 'simple string replace' for the address of API in the generated main*.js files? Would there be any side effects?
推荐答案
您可以在配置文件中外包您的 api 端点.并提供一个 AppInitializer
来使用你的配置文件.下面是一个例子:
You can outsource your api endpoint in a config file. And provide an AppInitializer
to use your config file.
Here is an example:
loader 函数,它通过 http 从 /config/config.json
加载配置并设置 api 配置:
the loader function, which loads the config via http from /config/config.json
and sets the api configuration:
export function loadConfig(http: HttpClient, config: ApiConfiguration): (() => Promise<boolean>) {
return (): Promise<boolean> => {
return new Promise<boolean>((resolve: (a: boolean) => void): void => {
http.get('./config/config.json')
.pipe(
map((x: any) => {
config.rootUrl = x.rootUrl + '/v2';
resolve(true);
}),
catchError((x: { status: number }, caught: Observable<void>): ObservableInput<{}> => {
// 404 local development, other errors are strange
resolve(x.status === 404);
return of({});
})
).subscribe();
});
};
}
json 只包含一个名为 rootUrl
的字符串.
The json contains only one string named rootUrl
.
为了使用这个函数,在应用初始化之前,在你的 app.module.ts
中提供一个 AppInitializer
:
And to use this function, before the app initializes, provide an AppInitializer
in your app.module.ts
:
providers: [
{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [
HttpClient,
ApiConfiguration
],
multi: true
}
ApiConfiguration
存储 api 端点,它只是一个具有默认值的类(用于开发):
ApiConfiguration
stores the api endpoint which is just a class with a default value (for devlopment):
@Injectable({
providedIn: 'root',
})
export class ApiConfiguration {
rootUrl: string = 'localhost:8080';
}
只需将一个配置文件放在您的 /dist
文件夹中,它应该可以工作:)
Just put a config file in your /dist
folder and it should work :)
这篇关于构建后配置角度生产文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!