diff --git a/projects/ngx-stripe/src/lib/services/api-loader.service.ts b/projects/ngx-stripe/src/lib/services/api-loader.service.ts index 374033f..bdae2e7 100644 --- a/projects/ngx-stripe/src/lib/services/api-loader.service.ts +++ b/projects/ngx-stripe/src/lib/services/api-loader.service.ts @@ -1,10 +1,11 @@ -import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; +import { ApplicationRef, Inject, Injectable, isDevMode, PLATFORM_ID } from '@angular/core'; import { isPlatformServer } from '@angular/common'; -import { Observable, BehaviorSubject } from 'rxjs'; +import { Observable, BehaviorSubject, concatMap, timeout, catchError, EMPTY, shareReplay } from 'rxjs'; import { WindowRef } from './window-ref.service'; import { DocumentRef } from './document-ref.service'; +import { filter, first } from 'rxjs/operators'; export interface LazyStripeAPILoaderStatus { loaded: boolean; @@ -20,10 +21,30 @@ export class LazyStripeAPILoader { loading: false }); - constructor(@Inject(PLATFORM_ID) public platformId: any, public window: WindowRef, public document: DocumentRef) {} + private readonly isStable$ = this.applicationRef.isStable.pipe( + filter((stable) => stable), + timeout(10_000), + catchError(() => { + if (isDevMode()) { + console.warn(`Application failed to become stable within 10000ms. Loading the Stripe script now.`) + } + + return EMPTY; + }), + first(), + shareReplay(1) + ) + + constructor( + @Inject(PLATFORM_ID) public platformId: any, + public window: WindowRef, + public document: DocumentRef, + public applicationRef: ApplicationRef + ) {} public asStream(): Observable { - this.load(); + this.isStable$.subscribe(() => this.load()) + return this.status.asObservable(); }