import { Injectable } from '@angular/core'; import { StoreService } from './store.service'; import { Page } from '../model/page'; import { Root } from '../store/root'; import { Serializable } from '../model/serializable'; import { Tower } from '../model/tower'; import { Block } from '../model/block'; import { IPage } from '../interfaces/persistance/page'; import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject'; import { Observable } from 'rxjs/internal/Observable'; @Injectable({ providedIn: 'root' }) export class DataService extends Root { get pages(): Array { return this.children; } private readonly _safeChildren: BehaviorSubject> = new BehaviorSubject(null); readonly safeChildren$: Observable> = this._safeChildren.asObservable(); constructor(private storeService: StoreService>) { super(); this.init().catch(); } private async init() { const pages = await this.storeService.load(); Serializable.childrenMap = { Page: { childrenListName: 'towers', childrenConstructor: Tower }, Tower: { childrenListName: 'blocks', childrenConstructor: Block }, Block: { childrenListName: null, childrenConstructor: null } }; for (let page of pages) { new Page(this, page); } setTimeout(() => { this.children$.subscribe(value => { this.log(); }); }, 0); this.children$.subscribe(value => { this._safeChildren.next(value); this.save(0); }); } mutatedUpdate() { this.save(2500); } save(timeout: number) { this.storeService.scheduleSave(this.pages, timeout); } addPage(name: string) { const page = new Page(this, { name, userData: {}, towers: [] }); page.addTower(); } removePage(page: Page) { this.changeValue({ oldValue: this.children, newValue: this.children.filter(c => c !== page) }); } }