UNPKG

@ng-arthur/core

Version:

@ng-arthur/core for Angular 8+ Components

1,168 lines (1,135 loc) 37 kB
import { __decorate, __metadata, __param } from 'tslib'; import { Input, Directive, Injectable, Pipe, NgModule, ɵɵdefineInjectable, ɵɵinject, EventEmitter, Component, ViewEncapsulation, Output, ChangeDetectionStrategy, Inject, ElementRef, InjectionToken, Injector, APP_INITIALIZER, Optional, SkipSelf, INJECTOR } from '@angular/core'; import { TranslateDirective, TranslatePipe, TranslateModule, TranslateService, TranslateLoader } from '@ngx-translate/core'; import { BehaviorSubject, of, throwError, forkJoin } from 'rxjs'; import { filter, share, switchMap, map, tap, catchError } from 'rxjs/operators'; import { CommonModule, DOCUMENT } from '@angular/common'; import { configure, start, done } from 'nprogress'; import QRCode from 'qrcode'; import { HttpClient } from '@angular/common/http'; import { NaUtils } from '@ng-arthur/common'; import merge from 'deepmerge'; import { Meta, Title } from '@angular/platform-browser'; import { ActivatedRoute } from '@angular/router'; let NaI18NDirective = class NaI18NDirective { constructor(translate) { this.translate = translate; } set naI18n(key) { this.translate.translate = key; } set naI18nParams(params) { this.translate.translateParams = params; } }; __decorate([ Input(), __metadata("design:type", String), __metadata("design:paramtypes", [String]) ], NaI18NDirective.prototype, "naI18n", null); __decorate([ Input(), __metadata("design:type", Object), __metadata("design:paramtypes", [Object]) ], NaI18NDirective.prototype, "naI18nParams", null); NaI18NDirective = __decorate([ Directive({ selector: '[naI18n]' }), __metadata("design:paramtypes", [TranslateDirective]) ], NaI18NDirective); let NaI18NPipe = class NaI18NPipe { constructor(translate) { this.translate = translate; } transform(value, args) { return this.translate.transform(value, args); } }; NaI18NPipe = __decorate([ Injectable(), Pipe({ name: 'naI18N', pure: false // required to update the value when the promise is resolved }), __metadata("design:paramtypes", [TranslatePipe]) ], NaI18NPipe); let NaI18NModule = class NaI18NModule { }; NaI18NModule = __decorate([ NgModule({ imports: [ TranslateModule, ], exports: [ TranslateModule, NaI18NPipe, NaI18NDirective ], declarations: [ NaI18NPipe, NaI18NDirective ], }) ], NaI18NModule); let NaTranslateService = class NaTranslateService { constructor(translate) { this.translate = translate; this.change$ = new BehaviorSubject(new Object()); if (translate.getLangs() == null || translate.getLangs().length <= 0) { // translate.addLangs(['zh', 'en']); translate.addLangs([this.translate.getBrowserLang()]); } // if (this.translate.currentLang == null) { // this.translate.use(this.translate.getBrowserLang()); // } if (this.translate.getDefaultLang() == null) { // this.translate.setDefaultLang(this.translate.getBrowserCultureLang()); // zh_CN this.translate.setDefaultLang(this.translate.getBrowserLang()); // zh } } get change() { return this.change$.asObservable().pipe(filter(w => w != null)); } get currentLang() { return this.translate.currentLang; } /** * Gets the translated value of a key (or an array of keys) */ get(key, interpolateParams) { return this.translate.get(key, interpolateParams); } /** * Returns a stream of translated values of a key (or an array of keys) which updates * whenever the language changes. */ stream(key, interpolateParams) { return this.translate.stream(key, interpolateParams); } /** * Returns a translation instantly from the internal state of loaded translation. * All rules regarding the current language, the preferred language of even fallback languages will be used except any promise handling. */ instant(key, interpolateParams) { return this.translate.instant(key, interpolateParams); } /** * Changes the lang currently used */ use(lang) { this.change$.next(lang); return this.translate.use(lang); } /** * Sets the default language to use as a fallback */ setDefaultLang(lang) { this.translate.setDefaultLang(lang); } /** * Gets the default language used * @returns string */ getDefaultLang() { return this.translate.defaultLang; } /** * Returns an array of currently available langs * @returns any */ getLangs() { return this.translate.langs; } /** * @param langs * Add available langs */ addLangs(langs) { this.translate.addLangs(langs); } /** * Sets the translated value of a key */ set(key, value, lang = this.translate.currentLang) { this.translate.set(key, value, lang); } /** * Allows to reload the lang file from the file */ reloadLang(lang) { return this.translate.reloadLang(lang); } /** * Deletes inner translation */ resetLang(lang) { this.translate.resetLang(lang); } /** * Returns the language code name from the browser, e.g. "de" * * @returns string */ getBrowserLang() { return this.translate.getBrowserLang(); } /** * Returns the culture language code name from the browser, e.g. "de-DE" * * @returns string */ getBrowserCultureLang() { return this.translate.getBrowserCultureLang(); } }; NaTranslateService = __decorate([ Injectable(), __metadata("design:paramtypes", [TranslateService]) ], NaTranslateService); let NaI18NService = class NaI18NService extends NaTranslateService { }; NaI18NService.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaI18NService_Factory() { return new NaI18NService(ɵɵinject(TranslateService)); }, token: NaI18NService, providedIn: "root" }); NaI18NService = __decorate([ Injectable({ providedIn: 'root' }) ], NaI18NService); let NaMenuService = class NaMenuService { constructor(i18nSrv) { this.i18nSrv = i18nSrv; this._change$ = new BehaviorSubject([]); this.data = []; } get change() { return this._change$.pipe(share()); } getPathByUrl(url) { return null; } ngOnDestroy() { if (this._change$) { this._change$.unsubscribe(); } if (this.i18n$) { this.i18n$.unsubscribe(); } } }; NaMenuService.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaMenuService_Factory() { return new NaMenuService(ɵɵinject(NaI18NService)); }, token: NaMenuService, providedIn: "root" }); NaMenuService = __decorate([ Injectable({ providedIn: 'root' }), __metadata("design:paramtypes", [NaI18NService]) ], NaMenuService); let NaMessageService = class NaMessageService { success(content, options) { throw new Error(`请导入NaMessageService实现类, 错误信息: ${content}`); } error(content, options) { throw new Error(`请导入NaMessageService实现类, 错误信息: ${content}`); } info(content, options) { throw new Error(`请导入NaMessageService实现类, 错误信息: ${content}`); } warning(content, options) { throw new Error(`请导入NaMessageService实现类, 错误信息: ${content}`); } loading(content, options) { throw new Error(`请导入NaMessageService实现类, 错误信息: ${content}`); } hide() { } }; NaMessageService = __decorate([ Injectable() ], NaMessageService); let NaMessageModule = class NaMessageModule { }; NaMessageModule = __decorate([ NgModule({ imports: [ CommonModule ], providers: [ NaMessageService ] }) ], NaMessageModule); const DeleteEmptyFields = (target, propertyKey, descriptor, bindingPropertyName) => { console.log(target, propertyKey, descriptor, bindingPropertyName); function PropDecorator(_target, _name) { console.log(_target, _name); } return PropDecorator; }; function preloaderFinished() { const body = document.querySelector('body'); const preloader = document.querySelector('.preloader'); body.style.overflow = 'hidden'; function remove() { // preloader value null when running --hmr if (!preloader) { return; } preloader.addEventListener('transitionend', function () { preloader.className = 'preloader-hidden'; }); preloader.className += ' preloader-hidden-add preloader-hidden-add-active'; } window.appBootstrap = () => { setTimeout(() => { remove(); body.style.overflow = ''; }, 100); }; } let ProgressBarService = class ProgressBarService { constructor() { this.progressEmitter = new EventEmitter(); } start() { this.progressEmitter.emit(true); } done() { this.progressEmitter.emit(false); } }; ProgressBarService = __decorate([ Injectable(), __metadata("design:paramtypes", []) ], ProgressBarService); let ProgressBarComponent = class ProgressBarComponent { constructor(progressBarService) { this.progressBarService = progressBarService; // NProgressConfigureOptions this.options = { parent: '#container', showSpinner: false }; configure(this.options); this.progressEmitter$ = this.progressBarService.progressEmitter.subscribe((forceShow) => { if (forceShow) { start(); } else { done(); } }); } set progress(forceShow) { this.progressBarService.progressEmitter.emit(forceShow); } ngOnDestroy() { if (this.progressEmitter$) { this.progressEmitter$.unsubscribe(); } } ngAfterViewInit() { } ngAfterContentInit() { // NProgress.start(); } ngOnChanges(changes) { // console.log(changes['progress']); } }; __decorate([ Input(), __metadata("design:type", Object) ], ProgressBarComponent.prototype, "options", void 0); __decorate([ Input(), __metadata("design:type", Boolean), __metadata("design:paramtypes", [Boolean]) ], ProgressBarComponent.prototype, "progress", null); ProgressBarComponent = __decorate([ Component({ selector: 'na-progress-bar', template: "<div id=\"container\" style=\"height: 100%;\">\n <ng-content></ng-content>\n</div>\n", encapsulation: ViewEncapsulation.None, styles: ["#nprogress{pointer-events:none}#nprogress .bar{background:#29d;position:fixed;z-index:1031;top:0;left:0;width:100%;height:2px}#nprogress .peg{display:block;position:absolute;right:0;width:100px;height:100%;box-shadow:0 0 10px #29d,0 0 5px #29d;opacity:1;-webkit-transform:rotate(3deg) translate(0,-4px);transform:rotate(3deg) translate(0,-4px)}#nprogress .spinner{display:block;position:fixed;z-index:1031;top:15px;right:15px}#nprogress .spinner-icon{width:18px;height:18px;box-sizing:border-box;border:2px solid transparent;border-top-color:#29d;border-left-color:#29d;border-radius:50%;-webkit-animation:.4s linear infinite nprogress-spinner;animation:.4s linear infinite nprogress-spinner}.nprogress-custom-parent{overflow:hidden;position:relative}.nprogress-custom-parent #nprogress .bar,.nprogress-custom-parent #nprogress .spinner{position:absolute}@-webkit-keyframes nprogress-spinner{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes nprogress-spinner{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}"] }), __metadata("design:paramtypes", [ProgressBarService]) ], ProgressBarComponent); let ProgressBarModule = class ProgressBarModule { }; ProgressBarModule = __decorate([ NgModule({ imports: [ CommonModule ], exports: [ ProgressBarComponent ], declarations: [ ProgressBarComponent ], providers: [ ProgressBarService ] }) ], ProgressBarModule); let NaQRCodeComponent = class NaQRCodeComponent { constructor(el, _doc) { this.el = el; this._doc = _doc; this.urlChange = new EventEmitter(); this.level = 'M'; /** * 定义周边区域应该有多宽。 */ this.margin = 0; this.type = 'image/jpeg'; /** * Height/Width */ this.size = 256; // /** // * 宽度 // */ // @Input() width = 256; // /** // * 高度 // */ // @Input() height: number; /** * 前景色,值必须为十六进制格式(RGBA) */ this.colorDark = '#000000'; /** * 背景色,值必须为十六进制格式(RGBA) */ this.colorLight = '#ffffff'; this.isValidQrCodeText = (data) => { // if (this.allowEmptyString === false) { // return !(typeof data === 'undefined' || data === ''); // } return !(typeof data === 'undefined'); }; } ngOnInit() { QRCode.toDataURL(this._doc.getElementById('canvas'), this.data, { version: this.version, errorCorrectionLevel: this.level, margin: this.margin, width: this.size, color: { dark: this.colorDark, light: this.colorLight }, type: this.type, rendererOpts: { quality: 0.3 } }) .then(url => { this.urlChange.emit(url); }) .catch(err => { console.error(err); }); } ngOnChanges(changes) { const data = changes['data']; if (data && this.isValidQrCodeText(data.currentValue)) ; } }; __decorate([ Input(), __metadata("design:type", Number) ], NaQRCodeComponent.prototype, "version", void 0); __decorate([ Input(), __metadata("design:type", String) ], NaQRCodeComponent.prototype, "data", void 0); __decorate([ Input(), __metadata("design:type", String) ], NaQRCodeComponent.prototype, "url", void 0); __decorate([ Output(), __metadata("design:type", Object) ], NaQRCodeComponent.prototype, "urlChange", void 0); __decorate([ Input(), __metadata("design:type", String) ], NaQRCodeComponent.prototype, "level", void 0); __decorate([ Input(), __metadata("design:type", Object) ], NaQRCodeComponent.prototype, "margin", void 0); __decorate([ Input(), __metadata("design:type", String) ], NaQRCodeComponent.prototype, "type", void 0); __decorate([ Input(), __metadata("design:type", Object) ], NaQRCodeComponent.prototype, "size", void 0); __decorate([ Input(), __metadata("design:type", Object) ], NaQRCodeComponent.prototype, "colorDark", void 0); __decorate([ Input(), __metadata("design:type", Object) ], NaQRCodeComponent.prototype, "colorLight", void 0); NaQRCodeComponent = __decorate([ Component({ selector: 'na-qrcode', template: "<canvas id=\"canvas\"></canvas>\n", changeDetection: ChangeDetectionStrategy.OnPush, styles: [""] }), __param(1, Inject(DOCUMENT)), __metadata("design:paramtypes", [ElementRef, Object]) ], NaQRCodeComponent); let NaQRCodeService = class NaQRCodeService { constructor() { } /** * Creates QR Code symbol and returns a qrcode object. */ // create(text: string | QRCodeSegment[], options: QRCodeOptions): QRCode.QRCode { create(text, options) { return QRCode.create(text, options); } /** * Draws qr code symbol to canvas. */ toCanvas(text, options, canvas) { if (canvas) { return QRCode.toCanvas(canvas, text, options); } return QRCode.toCanvas(text, options); } /** * Returns a Data URI containing a representation of the QR Code image. */ toDataURL(text, options, canvasElement) { if (canvasElement) { return QRCode.toDataURL(canvasElement, text, options); } return QRCode.toDataURL(text, options); } /** * Returns a string representation of the QR Code. * If choosen output format is svg it will returns a string containing xml code. */ toString(text, options) { return QRCode.toString(text, options); } /** * Saves QR Code to image file. * If options.type is not specified, the format will be guessed from file extension. * Recognized extensions are png, svg, txt. */ toFile(path, text, options) { return QRCode.toFile(path, text, options); } /** * Writes QR Code image to stream. Only works with png format for now. */ toFileStream(streamW, text, options) { return QRCode.toFileStream(streamW, text, options); } }; NaQRCodeService = __decorate([ Injectable(), __metadata("design:paramtypes", []) ], NaQRCodeService); let NaQRCodeModule = class NaQRCodeModule { }; NaQRCodeModule = __decorate([ NgModule({ imports: [], exports: [ NaQRCodeComponent ], providers: [ NaQRCodeService ], declarations: [NaQRCodeComponent] }) ], NaQRCodeModule); let NaSettingsComponent = class NaSettingsComponent { constructor() { } ngOnInit() { } }; NaSettingsComponent = __decorate([ Component({ selector: 'na-settings', template: "<p>\n settings works!\n</p>\n", styles: [""] }), __metadata("design:paramtypes", []) ], NaSettingsComponent); let NaSettingsModule = class NaSettingsModule { }; NaSettingsModule = __decorate([ NgModule({ imports: [ CommonModule ], declarations: [NaSettingsComponent] }) ], NaSettingsModule); let NaSettingsService = class NaSettingsService { constructor() { } }; NaSettingsService.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaSettingsService_Factory() { return new NaSettingsService(); }, token: NaSettingsService, providedIn: "root" }); NaSettingsService = __decorate([ Injectable({ providedIn: 'root' }), __metadata("design:paramtypes", []) ], NaSettingsService); const NA_STARTUP_CONFIG = new InjectionToken('NA_STARTUP_CONFIG'); /** * 用于应用启动时 * * 一般用来获取应用所需要的基础数据等 * * @export */ let NaStartupService = class NaStartupService { constructor(client) { this.client = client; this._startupConfig = {}; this.initialized = false; this.cache = new Map(); } /** * 启动加载 * * TODO ssr注入`HttpClient`在使用client时会有异常 * @param startupConfig 启动配置文件 */ /* load(startupConfig: IStartupConfigResource): Promise<any | void> { return new Promise((resolve, reject) => { const filePath = startupConfig.prefix + startupConfig.suffix; this.client.get(filePath).subscribe( (next: any) => { const rtnData = Object.assign({}, next); const profiles = next.profiles; if (profiles && profiles.active) { const file = startupConfig.prefix + '-' + profiles.active + startupConfig.suffix; const params = {}; // params[NaConstant.HTTP.RTN_ERROR_PROMPT] = false; this.client.get(file, {params: params}).subscribe( data => { NaUtils.mergeJSON(rtnData, data); console.log(data, rtnData); resolve(true); }, err => { console.log(err); reject(err); }, () => { this._startupConfig = rtnData; } ); } }, error => { console.error(`the profiles does not exist or error. please check the profiles active.`, error); reject(error); } ); }); } */ load(startupConfig) { const filePath = startupConfig.prefix + startupConfig.suffix; return this.client.get(filePath).pipe(switchMap((value) => { const rtnData = Object.assign({}, value); const profiles = rtnData.profiles; if (profiles && profiles.active) { const file = startupConfig.prefix + '-' + profiles.active + startupConfig.suffix; const params = {}; // params[NaConstant.HTTP.RTN_ERROR_PROMPT] = false; return this.client.get(file, { params: params }).pipe(map((resp) => { NaUtils.mergeJSON(rtnData, resp); return rtnData; })); } else { return of(rtnData); } }), tap(next => { this._startupConfig = next; this.initialized = true; }), catchError(err => { console.error(`the profiles does not exist or error. please check the profiles active.`, err); return throwError(err); })) .toPromise(); } get(key) { if (!this.initialized) { throw new Error('未加载完毕!'); } return this.getValue(this._startupConfig, key); } getValue(target, key) { if (this.cache.has(key)) { return this.cache.get(key); } const keys = key.split('.'); key = ''; do { key += keys.shift(); if (NaUtils.isDefined(target) && NaUtils.isDefined(target[key]) && (typeof target[key] === 'object' || !keys.length)) { target = target[key]; key = ''; } else if (!keys.length) { target = undefined; } else { key += '.'; } } while (keys.length); this.cache.set(key, target); return target; } }; NaStartupService = __decorate([ Injectable(), __metadata("design:paramtypes", [HttpClient]) ], NaStartupService); function throwIfAlreadyLoaded(parentModule, moduleName) { if (parentModule) { throw new Error(`${moduleName} has already been loaded. Import ${moduleName} modules in the AppModule only.`); } } /** * 其他翻译资源 */ const NA_TRANSLATE_RESOURCES = new InjectionToken('NA_TRANSLATE_RESOURCES'); class MultiTranslateHttpLoader { constructor(http, resources, injector) { this.http = http; this.resources = resources; this.injector = injector; } /** * 获取翻译资源 * * @param lang 语言 */ getTranslation(lang) { const obs = []; const translateResources = this.injector.get(NA_TRANSLATE_RESOURCES, []); translateResources.forEach(tr => { obs.push(tr.getTranslation(lang).pipe(catchError(err => { console.error('获取翻译资源失败!', err); return of({}); }))); }); const requests = this.resources.map(resource => { return this.http.get(resource.prefix + lang + resource.suffix).pipe(catchError(err => { console.error('获取翻译资源失败!', err); return of({}); })); }); obs.push(...requests); // const merge = require('deepmerge').default; return forkJoin(obs).pipe(map(response => { const mergeResponse = []; response.forEach(item => { if (item) { mergeResponse.push(item); } }); // 如果response数组内存在null,这里会报错 return merge.all(mergeResponse); })); } } var NaTranslateModule_1; const NA_DEFAULT_RESOURCES = new InjectionToken('NA_DEFAULT_RESOURCES'); function createTranslateLoader(http, resources, injector) { return new MultiTranslateHttpLoader(http, resources, injector); } let NaTranslateModule = NaTranslateModule_1 = class NaTranslateModule { static forRoot(resources = []) { return { ngModule: NaTranslateModule_1, providers: [ { provide: NA_DEFAULT_RESOURCES, useValue: resources }, ...TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [HttpClient, NA_DEFAULT_RESOURCES, Injector] }, // 隔离服务 isolate: true, useDefaultLang: true }).providers ] }; } }; NaTranslateModule = NaTranslateModule_1 = __decorate([ NgModule({ imports: [ TranslateModule ], exports: [ TranslateModule, ], providers: [ NaTranslateService ] }) ], NaTranslateModule); var NaStartupModule_1; let NaStartupModule = NaStartupModule_1 = class NaStartupModule { constructor(parentModule) { throwIfAlreadyLoaded(parentModule, 'NaStartupModule'); } static forRoot(startupConfig) { return { ngModule: NaStartupModule_1, providers: [ { provide: NA_STARTUP_CONFIG, useValue: startupConfig }, NaStartupService, { provide: APP_INITIALIZER, useFactory: NaStartupServiceFactory, deps: [NaStartupService, NA_STARTUP_CONFIG], multi: true, } ] }; } }; NaStartupModule = NaStartupModule_1 = __decorate([ NgModule({ imports: [ NaTranslateModule ] }), __param(0, Optional()), __param(0, SkipSelf()), __metadata("design:paramtypes", [NaStartupModule]) ], NaStartupModule); function NaStartupServiceFactory(startupService, startupConfig) { const initializer = () => { return startupService.load(startupConfig); }; return initializer; } let NaMetaService = class NaMetaService { constructor(meta) { this.meta = meta; } addTag(tag, forceCreation) { return this.meta.addTag(tag, forceCreation); } addTags(tags, forceCreation) { return this.meta.addTags(tags, forceCreation); } getTag(attrSelector) { return this.meta.getTag(attrSelector); } getTags(attrSelector) { return this.meta.getTags(attrSelector); } updateTag(tag, selector) { return this.meta.updateTag(tag, selector); } removeTag(attrSelector) { this.meta.removeTag(attrSelector); } removeTagElement(meta) { this.meta.removeTagElement(meta); } }; NaMetaService.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaMetaService_Factory() { return new NaMetaService(ɵɵinject(Meta)); }, token: NaMetaService, providedIn: "root" }); NaMetaService = __decorate([ Injectable({ providedIn: 'root' }), __metadata("design:paramtypes", [Meta]) ], NaMetaService); // import { MenuService } from '../menu/menu.service'; // import { ALAIN_I18N_TOKEN, AlainI18NService } from '../i18n/i18n'; let NaTitleService = class NaTitleService { constructor(injector, title, // private menuSrv: MenuService, // @Optional() // @Inject(ALAIN_I18N_TOKEN) // private i18nSrv: AlainI18NService, doc) { this.injector = injector; this.title = title; this.doc = doc; this._prefix = ''; this._suffix = ''; this._separator = ' - '; this._reverse = false; this._default = 'Not Page Name'; // if (this.i18nSrv) { // this.i18n$ = this.i18nSrv.change.subscribe(() => this.setTitle()); // } } /** 设置分隔符 */ set separator(value) { this._separator = value; } /** 设置前缀 */ set prefix(value) { this._prefix = value; } /** 设置后缀 */ set suffix(value) { this._suffix = value; } /** 设置是否反转 */ set reverse(value) { this._reverse = value; } /** 设置默认标题名 */ set default(value) { this._default = value; } getByElement() { const el = this.doc.querySelector('.content__title h1') || this.doc.querySelector('pro-header h1.title'); if (el) { return el.firstChild.textContent.trim(); } return ''; } getByRoute() { let next = this.injector.get(ActivatedRoute); while (next.firstChild) { next = next.firstChild; } const data = (next.snapshot && next.snapshot.data) || {}; // if (data.titleI18n && this.i18nSrv) { // data.title = this.i18nSrv.fanyi(data.titleI18n); // } return data.title; } getByMenu() { // const menus = this.menuSrv.getPathByUrl(this.injector.get(Router).url); // if (!menus || menus.length <= 0) { // return ''; // } // const item = menus[menus.length - 1]; // let title; // if (item.i18n && this.i18nSrv) { // title = this.i18nSrv.fanyi(item.i18n); // } // return title || item.text; return null; } /** * 设置标题,若不指定具体名称,则按以顺序获取: * - 路由配置 `{ data: { title: 'page name' } }` * - 根据当前 URL 解析菜单数据 * - 页面 `content__title` 中获取 `h1` 内容 * - 默认标题名 */ setTitle(title) { if (!title) { title = this.getByRoute() || this.getByMenu() || this.getByElement() || this._default; } if (title && !Array.isArray(title)) { title = [title]; } let newTitles = []; if (this._prefix) { newTitles.push(this._prefix); } newTitles.push(...title); if (this._suffix) { newTitles.push(this._suffix); } if (this._reverse) { newTitles = newTitles.reverse(); } this.title.setTitle(newTitles.join(this._separator)); } ngOnDestroy() { if (this.i18n$) { this.i18n$.unsubscribe(); } } }; NaTitleService.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaTitleService_Factory() { return new NaTitleService(ɵɵinject(INJECTOR), ɵɵinject(Title), ɵɵinject(DOCUMENT)); }, token: NaTitleService, providedIn: "root" }); NaTitleService = __decorate([ Injectable({ providedIn: 'root' }), __param(2, Inject(DOCUMENT)), __metadata("design:paramtypes", [Injector, Title, Object]) ], NaTitleService); // #docregion // #docregion storage-token const BROWSER_STORAGE = new InjectionToken('Browser Storage', { providedIn: 'root', factory: () => localStorage }); // #enddocregion storage-token // #docregion inject-storage-token // @Injectable({ // providedIn: 'root' // }) class BrowserStorageService { /** * 设置缓存值 * * @param {string} key 主键 * @param {any} value 数据 * @param {number} [expires] 过期时间的秒数 * @memberof NaLocalStorageService */ set(key, value, expires) { const obj = new Object(); obj['data'] = value; if (expires != null) { obj['expires'] = (new Date().getTime() + expires * 1000); } this.storage.setItem(key, JSON.stringify(obj)); } /** * 获取缓存值 * * @param {string} key * @returns {any} * @memberof BrowserStorageService */ get(key) { return this.getValidData(key); } remove(key) { this.storage.removeItem(key); } getValidData(key) { const value = this.storage.getItem(key); try { const _value = JSON.parse(value); if (_value) { if (_value['expires'] == null || _value['expires'] >= new Date().getTime()) { return _value['data']; } else { // 数据已过期 this.remove(key); } } return null; } catch (error) { return value; } } } function _localStorage() { return localStorage; } const BROWSER_LOCALSTORAGE = new InjectionToken('Browser LocalStorage', { providedIn: 'root', factory: _localStorage }); /** * localStorage生命周期是永久 * 只能存储字符串类型的对象 * * @export */ let NaLocalStorageService = class NaLocalStorageService extends BrowserStorageService { constructor(storage) { super(); this.storage = storage; this.storage = storage; } }; NaLocalStorageService = __decorate([ Injectable(), __param(0, Inject(BROWSER_LOCALSTORAGE)), __metadata("design:paramtypes", [Object]) ], NaLocalStorageService); function _sessionStorage() { return sessionStorage; } // #docregion storage-token const BROWSER_SESSIONSTORAGE = new InjectionToken('Browser SessionStorage', { providedIn: 'root', factory: _sessionStorage }); // #enddocregion storage-token let NaSessionStorageService = class NaSessionStorageService extends BrowserStorageService { constructor(storage) { super(); this.storage = storage; this.storage = storage; } }; NaSessionStorageService = __decorate([ Injectable(), __param(0, Inject(BROWSER_SESSIONSTORAGE)), __metadata("design:paramtypes", [Object]) ], NaSessionStorageService); let NaSelectivePreloadStrategy = class NaSelectivePreloadStrategy { constructor() { this.preloadedModules = []; } preload(route, load) { if (route.data && route.data['preload']) { // add the route path to our preloaded module array this.preloadedModules.push(route.path); // log the route path to the console // console.log('Preloaded: ' + route.path); return load(); } else { return of(null); } } }; NaSelectivePreloadStrategy.ngInjectableDef = ɵɵdefineInjectable({ factory: function NaSelectivePreloadStrategy_Factory() { return new NaSelectivePreloadStrategy(); }, token: NaSelectivePreloadStrategy, providedIn: "root" }); NaSelectivePreloadStrategy = __decorate([ Injectable({ providedIn: 'root' }) ], NaSelectivePreloadStrategy); /** * 把应用级、只用一次的组件收集到NaCoreModule中 * * @export */ let NaCoreModule = class NaCoreModule { constructor(parentModule) { throwIfAlreadyLoaded(parentModule, 'NaCoreModule'); } }; NaCoreModule = __decorate([ NgModule({ exports: [ // CommonModule, // BrowserModule, // BrowserAnimationsModule, NaMessageModule ], providers: [ NaLocalStorageService, NaSessionStorageService, NaSelectivePreloadStrategy, ] }), __param(0, Optional()), __param(0, SkipSelf()), __metadata("design:paramtypes", [NaCoreModule]) ], NaCoreModule); export { BROWSER_LOCALSTORAGE, BROWSER_SESSIONSTORAGE, DeleteEmptyFields, MultiTranslateHttpLoader, NA_DEFAULT_RESOURCES, NA_STARTUP_CONFIG, NA_TRANSLATE_RESOURCES, NaCoreModule, NaI18NDirective, NaI18NModule, NaI18NPipe, NaI18NService, NaLocalStorageService, NaMenuService, NaMessageModule, NaMessageService, NaMetaService, NaQRCodeComponent, NaQRCodeModule, NaQRCodeService, NaSelectivePreloadStrategy, NaSessionStorageService, NaSettingsComponent, NaSettingsModule, NaSettingsService, NaStartupModule, NaStartupService, NaStartupServiceFactory, NaTitleService, NaTranslateModule, NaTranslateService, ProgressBarComponent, ProgressBarModule, ProgressBarService, _localStorage, _sessionStorage, createTranslateLoader, preloaderFinished, throwIfAlreadyLoaded, BrowserStorageService as ɵa }; //# sourceMappingURL=ng-arthur-core.js.map