forked from marcj/angular2-localstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalStorageEmitter.ts
53 lines (43 loc) · 1.52 KB
/
LocalStorageEmitter.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
import {Injectable, OnDestroy} from "@angular/core";
import {NgZone} from "@angular/core";
export class LocalStorageEmitter {
protected static subscribed: any = [];
protected static ngZones: NgZone[] = [];
public static register(ngZone: NgZone) {
let index: number = LocalStorageEmitter.ngZones.indexOf(ngZone);
if (index === -1) {
index = LocalStorageEmitter.ngZones.push(ngZone) - 1;
}
LocalStorageEmitter.subscribed[index] = ngZone.onMicrotaskEmpty.subscribe(() => {
for (let callback of LocalStorageEmitter.subscribers) {
callback();
}
});
}
protected static subscribers: any = [];
public static subscribe(callback: Function) {
LocalStorageEmitter.subscribers.push(callback);
}
public static unregister(ngZone: NgZone) {
let index: number = LocalStorageEmitter.ngZones.indexOf(ngZone);
if (index >= 0) {
LocalStorageEmitter.subscribed[index].unsubscribe();
}
}
}
@Injectable()
export class LocalStorageService implements OnDestroy {
constructor(private ngZone: NgZone) {
LocalStorageEmitter.register(this.ngZone);
}
ngOnDestroy() {
LocalStorageEmitter.unregister(this.ngZone);
}
}
import {Type} from "@angular/core";
import {ComponentRef} from "@angular/core";
export function LocalStorageSubscriber(appPromise: Promise<ComponentRef<any>>) {
appPromise.then((bla) => {
bla.injector.get(<Type<any>>LocalStorageService);
});
}