2015-10-16 54 views
2

我在基于Node中的环境变量的Angular应用程序中的index.html文件底部有一个脚本。我想用一个公共api密钥进行分段,另一个用于生产。如何在基于Nodejs中的环境变量的Angular中插入动态脚本

我使用相同的grunt构建用于分段和生产,所以我不知道如果动态更改构建的常量,建议here是最佳解决方案。

有关如何处理这个问题的任何想法?

当环境变量是NODE_ENV =生产,插入此:

<script> 
Stripe.setPublishableKey('pk_live_NN4j94VX3mtz2wJtIO3bmH'); 
</script> 

当环境变量是NODE_ENV =分期,插入此:

<script> 
Stripe.setPublishableKey('pk_test_LgtEvbZwjC2GaKQYE3I6NnzuA'); 
</script> 
+0

构建时动态改变常量是真正实现它的唯一好方法,我不知道你会如何处理它。 SOMEWHERE你需要读入或切换一个环境变量,如果这个变量恰好是你的构建控件的一部分,那么这是一个可以放置的地方。如果你想要一个角度较小的解决方案,那么你可以在角度构建之前包含一个全局配置js脚本。 – tommybananas

+0

创建配置模块可能不是一个坏主意。 (基本上是一个导出的JSON对象),以便您可以使用基于环境变量的变量。 –

回答

1

我会用grunt-ng-constant来管理角度的环境变量然后在您的角度app.config()函数内部初始化Stripe而不是文档。

我的首选是使用angular-stripe来管理角启动过程中的Stripe。如果使用两个密钥配置应用程序,这也可能使您的工作更轻松。以下是我的一个应用程序的一些示例代码。

var $app = angular.module('app', ['angular-stripe']); 
$app.constant('devDomains', ['localhost', 'staging.mydomain.com']); 
$app.constant('stripePubKeyStaging', 'STRIPE_PUB_KEY_HERE'); 
$app.constant('stripePubKey', 'STRIPE_PUB_KEY_HERE'); 

$app.config(function(devDomains, stripePubKey, stripePubKeyStaging, stripeProvider) { 
    if (devDomains.indexOf(document.location.hostname) !== -1 || document.location.search.indexOf('stripe-test-key') !== -1) { 

    // if you're running your angular app on local or staging, use the test key. Additionally 
    // if you load your page with ?stripe-test-key you can force your production app 
    // to use the test key in order to debug something on live if you'd like. 
    stripeProvider.setPublishableKey(stripePubKeyStaging); 
    } else { 
    stripeProvider.setPublishableKey(stripePubKey); 
    } 
}); 
相关问题