如何从Angular组件获取变量注入NgModule配置NgxStripe用户专属密钥
解决方案
首先明确一个前提:Angular 模块的 forRoot 配置是在应用启动/模块加载的静态阶段执行的,此时组件还未完成实例化,不可能直接获取组件内的变量。你这种需要按用户维度动态获取 Stripe 密钥的场景,不需要在 @NgModule 的 imports 里静态传参,用 ngx-stripe 提供的动态初始化能力即可,具体步骤如下:
- 第一步:调整模块中 NgxStripeModule 的引入方式,不需要传入静态密钥:
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgxStripeModule.forRoot(), // 此处无需传入固定密钥 LibraryModule ], providers: [], bootstrap: [AppComponent] })
- 第二步:在需要调用支付的组件中,先从后端接口请求到当前用户对应的 Stripe 发布密钥,再调用
StripeService提供的方法动态初始化:
import { StripeService } from 'ngx-stripe'; import { HttpClient } from '@angular/common/http'; @Component({ // 你的组件原有配置 }) export class YourPaymentComponent { constructor( private http: HttpClient, private stripeService: StripeService ) {} ngOnInit() { // 先请求后端获取当前用户对应的Stripe发布密钥 this.http.get<{stripePublishKey: string}>('/api/你的用户密钥接口地址').subscribe(res => { // 动态初始化Stripe实例 this.stripeService.load(res.stripePublishKey); // 低版本ngx-stripe可替换为 this.stripeService.setKey(res.stripePublishKey) }); } // 后续调用支付逻辑直接使用stripeService即可,无需重复传入密钥 }
- 注意事项:
- 调用 Stripe 支付相关逻辑前,请确保
load()/setKey()方法已经执行完成,可以加状态位判断或者用RxJS流控制执行顺序,避免出现Stripe未初始化的报错。
- 调用 Stripe 支付相关逻辑前,请确保
内容的提问来源于stack exchange,提问作者Sergio Cano
相关产品推荐
相关产品推荐

