我没有完全理解你的问题,我可以想到两种方法来实现这一点:
A- 生成新项目时传递参数:
1- 为了能够将参数传递给 angular cli,您需要了解您希望在哪里使用它。
如果您的布局中使用了这些配置,您可以分叉 Angular cli 并更新它的蓝图并轻松添加您自己的配置。
这是组件蓝图:
angular-cli/packages/@angular/cli/blueprints/component/files/__path__/__name__.component.ts
看起来像这样:
@Component({
selector: '<%= selector %>',<% if(inlineTemplate) { %>
template: `
你看到selector 了吗?这是您可以使用的组件的名称,最后当您创建一个新项目时,您可以在那里传递您自己的标志并使用它。
但这不是最好的主意,因为当 Angular cli 更新时,您总是会遇到麻烦。
2- 另一个可能的解决方案是使用ng eject
这将在一个单独的文件中生成webpack 配置并将其放在您的项目根文件夹中,然后您可以使用该文件并提供您的配置并根据您的应用对其进行自定义。
但同样,我不确定您想如何使用该配置。
这是您build time 配置的完美候选。
3- 使用environments 配置:
已经回答了,这也很方便提供build time的配置:
关注@mikedanylov 的回答,然后在您的文件中像这样使用它:
import { environment } from './environments/environment';
if(environment.colorRed==='blue'){
console.log('the color is blue');
}
npm build -e=colorRed
乙:Run time:
这是一个更好的选择,您可以像这样在 index.html 中创建一个调用:
<script src="wherever/configurations/blue"></script>
然后在配置里面,你可能有:
var configuration = {
whatEver:"blue"
}
因为这是一个脚本,它可以在任何地方使用,您可以在您的组件中访问它:
export class MyComponent{
ngOnInit(){
console.log('colour is : '+window['configuration.whatEver']); // obviously you can improve this and create type definitions and what not.
}
}
这将使您在将来更新配置时更加灵活,而无需重新构建您的应用。
显然,您可以通过 Ajax 调用进行相同的调用,但我发现上面的调用与应用程序无关。