简体   繁体   English

如何在 AppNgModule forRoot() 中添加动态值?

[英]How to add dynamic value in AppNgModule forRoot()?

I have searched a lot but didn't find any solution yet.我已经搜索了很多,但还没有找到任何解决方案。

NgxStripeModule.forRoot('publishable_key'),

I need this "publishable_key" should be dynamic and it will come from a REST API.我需要这个“publishable_key”应该是动态的,它将来自 REST API。

Is there any option to do that?有什么选择吗?

Thank you.谢谢你。

You first have to register the module with the forRoot method as a blank string NgxStripeModule.forRoot('') .您首先必须使用forRoot方法将模块注册为空白字符串NgxStripeModule.forRoot('') Later using APP_INITIALIZER make an API call, receive a settings, extract publishable_key and fill in that in strip API using stripeService.changeKey('publishable_key') method.稍后使用APP_INITIALIZER进行 API 调用,接收设置,提取publishable_key并使用stripeService.changeKey('publishable_key') method. This process will happen before the app bootstrap.此过程将在应用程序启动之前发生。 So no need to worry about picking up right settings.因此,无需担心选择正确的设置。

function initializeApp(http: HttpClient, stripeService: StripeService): Observable<any> {
  return http.get('api/url').pipe(
    tap((data) => stripeService.changeKey(data.publishable_key)) // or .setKey(...)
  );
}
@NgModule({
 imports: [
   ...,
   NgxStripeModule.forRoot(''),
 ],
 declarations: [...],
 bootstrap: [AppComponent],
 providers: [
  ...,
  {
   provide: APP_INITIALIZER,
   useFactory: initializeApp,
   multi: true,
   deps: [HttpClient, StripeService]
  }
 ]
})
export class AppModule {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM