import { ApplicationRef, ChangeDetectorRef, ElementRef, ViewChild } from "@angular/core"; export class ComponentBase { // 储存数据用 saveKey = ""; // 储存对象 item: any = {}; ngOnChanges() { } ngOnDestroy() { } constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) { } ngOnInit() { // 获取存储的数据 (<any>window).courseware.getData((data) => { if (data) { this.item = data; this.itemStr = JSON.stringify(this.item, null, 4).trim(); } this.init(); this.changeDetectorRef.markForCheck(); this.changeDetectorRef.detectChanges(); this.refresh(); }, this.saveKey); } @ViewChild("itemTextarea", { static: true }) itemTextarea: ElementRef; copyData() { this.itemTextarea.nativeElement.select(); document.execCommand("copy"); } /** * 储存图片数据 * @param e */ onAssetUploadSuccess(e: any, ...key: Array<string>) { let item = this.item; for (let i = 0; i < key.length; i++) { if (i + 1 == key.length) { item[key[i]] = e.url; this.save(); return; } item = item[key[i]]; } } save() { (<any>window).courseware.setData(this.item, null, this.saveKey); this.itemStr = JSON.stringify(this.item, null, 4).trim(); this.refresh(); console.log('this.item = ' + JSON.stringify(this.item)); } itemStr = ""; load() { this.itemStr = this.itemTextarea.nativeElement.value; if (this.isJSON(this.itemStr)) { this.item = JSON.parse(this.itemStr); this.init(); this.changeDetectorRef.markForCheck(); this.changeDetectorRef.detectChanges(); this.refresh(); } } isJSON(str) { if (typeof str == 'string') { try { var obj = JSON.parse(str); if (typeof obj == 'object' && obj) { return true; } return false; } catch (e) { return false; } } return false; } /** * 刷新 渲染页面 */ refresh() { setTimeout(() => { this.appRef.tick(); }, 1); } init() { } }