ohayolibs
Version:
Ohayo is a set of essential modules for ohayojp.
76 lines (65 loc) • 2.33 kB
text/typescript
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { ComponentRef, Injectable, OnDestroy } from '@angular/core';
import { OhayoConfigService, OhayoLoadingConfig } from '@ohayo/util';
import { Subject, Subscription, timer } from 'rxjs';
import { debounce } from 'rxjs/operators';
import { LoadingDefaultComponent } from './loading.component';
import { LoadingShowOptions } from './loading.types';
export class LoadingService implements OnDestroy {
private _overlayRef: OverlayRef;
private compRef: ComponentRef<LoadingDefaultComponent> | null = null;
private opt: LoadingShowOptions | null = null;
private cog: OhayoLoadingConfig;
private n$ = new Subject();
private loading$: Subscription;
get instance(): LoadingDefaultComponent | null {
return this.compRef != null ? this.compRef.instance : null;
}
constructor(private overlay: Overlay, configSrv: OhayoConfigService) {
this.cog = configSrv.merge('loading', {
type: 'spin',
text: '加载中...',
icon: {
type: 'loading',
theme: 'outline',
spin: true,
},
delay: 0,
})!;
this.loading$ = this.n$
.asObservable()
.pipe(debounce(() => timer(this.opt!.delay)))
.subscribe(() => this.create());
}
private create(): void {
if (this.opt == null) return;
this._close(false);
this._overlayRef = this.overlay.create({
positionStrategy: this.overlay.position().global().centerHorizontally().centerVertically(),
scrollStrategy: this.overlay.scrollStrategies.block(),
hasBackdrop: true,
backdropClass: 'loading-backdrop',
});
this.compRef = this._overlayRef.attach(new ComponentPortal(LoadingDefaultComponent));
Object.assign(this.instance, { options: this.opt });
this.compRef.changeDetectorRef.markForCheck();
}
open(options?: LoadingShowOptions): void {
this.opt = { ...this.cog, ...options };
this.n$.next();
}
private _close(cleanOpt: boolean): void {
if (cleanOpt) this.opt = null;
if (!this._overlayRef) return;
this._overlayRef.detach();
this.compRef = null;
}
close(): void {
this._close(true);
}
ngOnDestroy(): void {
this.loading$.unsubscribe();
}
}