This repository has been archived by the owner on Mar 29, 2024. It is now read-only.
/
dialog.ref.ts
56 lines (47 loc) · 1.59 KB
/
dialog.ref.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { OverlayRef } from "@angular/cdk/overlay";
import { InjectionToken } from "@angular/core";
import { Observable, PartialObserver, Subject } from "rxjs";
import { filter, take } from "rxjs/operators";
import { DialogContainer, DialogState } from "./dialog.container";
export const DIALOG_REF = new InjectionToken<DialogRef<any>>('DialogRef');
export class DialogRef<T, R = any> {
constructor(
private _overlayRef: OverlayRef,
private container: DialogContainer,
) {
this.container.onStateChange
.pipe(
filter(state => state === 'closed'),
take(1)
)
.subscribe(() => {
this._overlayRef.detach();
this._overlayRef.dispose();
this.onClose.next(this.value);
this.onClose.complete();
});
}
get onStateChange(): Observable<DialogState> {
return this.container.onStateChange;
}
/**
* @returns The overlayref that holds the dialog container.
*/
overlay() { return this._overlayRef }
/** Value holds the value passed on close() */
private value: R | null = null;
/**
* Emits the result of the dialog and closes the overlay.
*/
onClose = new Subject<R | null>()
/** onAction only emits if close() is called with action. */
onAction<T extends R>(action: T, observer: PartialObserver<T> | ((value: T) => void)): this {
(this.onClose.pipe(filter(val => val === action)) as Observable<T>)
.subscribe(observer as any); // typescript does not select the correct type overload here.
return this;
}
close(result?: R) {
this.value = result || null;
this.container._startExit();
}
}