在Angular(Type Script)中有许多配置文件。哪一个是保存全局设置的正确方法?
例如,当我从本地调用API时,我的rootUrl
是localhost:42000
,但当我打开生产时,它应该是http:www.someting.com
。
我想把这个rootUrl
保存在全球某个地方,所以如果我打开生产,那么我只需要更改这个rootUrl
。
请建议我应该将这些全局设置保存在哪里,与Asp中的web.config相同。网
这个答案类似于@trimetriche,但没有更多关于代码的细节。
用于development/testing
目的
环境.ts
export const environment = {
production: false,
appUrl: 'localhost:4200'
};
对于production
环境产品
export const environment = {
production: true,
appUrl: 'mywebsite.com'
};
使用
服务.ts
import { environment } from '../../environments/environment';
this._http.get(environment.appUrl, requestHeaders(options));
记下所有environment
文件中的production
参数。我相信您还可以创建更多像environment.unittesting.ts
这样的环境。
当我第一次开始使用Angular 2时,我使用了一个global.ts文件,我把所有的变量都放在那里,这样我就可以很容易地更改它。
然后我发现了angular CLI提供的环境。您所要做的就是将文件命名为environment.prod.ts
(用于prod),并在构建时使用ng build --prod
。在开发时,使用environment.ts
文件,两个文件必须具有相同的变量。
我希望这能回答你的问题。
我有另一种定义全局设置的方法。因为如果我们在ts文件中定义,那么如果在生产模式中构建,就不容易找到常量来更改值。
export class SettingService {
constructor(private http: HttpClient) {
}
public getJSON(file): Observable<any> {
return this.http.get("./assets/configs/" + file + ".json");
}
public getSetting(){
// use setting here
}
}
在应用程序文件夹中,我添加文件夹configs/setting.json
设置中的内容.json
{
"baseUrl": "http://localhost:52555"
}
应用内模块添加app_INITIALIZER
{
provide: APP_INITIALIZER,
useFactory: (setting: SettingService) => function() {return setting.getSetting()},
deps: [SettingService],
multi: true
}
通过这种方式,我可以更容易地更改json文件中的值。
我在baseUrl、日期格式、会话输出的项目中应用了这个。。。
您可以很容易地将process.env
与webpack一起使用。例如
/**
* This interface makes sure we don't miss adding a property to both `prod` and `test`
*/
interface Config {
someItem: string;
}
/**
* We only export a single thing. The config.
*/
export let config: Config;
/**
* `process.env.NODE_ENV` definition is driven from webpack
*
* The whole `else` block will be removed in the emitted JavaScript
* for a production build
*/
if (process.env.NODE_ENV === 'production') {
config = {
someItem: 'prod'
}
console.log('Running in prod');
} else {
config = {
someItem: 'test'
}
console.log('Running in test');
}
您可以使用webpack -p --define process.env.NODE_ENV='"production"' --config ./src/webpack.config.js
更改process.env.NODE_ENV
更多
https://basarat.gitbooks.io/typescript/docs/tips/build-toggles.html