简体   繁体   中英

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.

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('') . 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. 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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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