How to add dynamic value in AppNgModule forRoot()?

Viewed 56

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.

1 Answers

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 {}
Related