Angular国际化,懒加载,动态添加Base
Angular做了国际化之后会生成不同语言的目录,加上在js文件是上传到后台项目中,通过域名加载js,js文件路径比较深,但js的加载是默认从根目录开始。
所以懒加载模块的时候总是报404错。经过查阅资料发现可以在模块加载前动态添加一个<base> tag,模块加载完成后再移除。
import {ElementRef, Injectable, Renderer2, RendererFactory2} from '@angular/core'; import {filter} from 'rxjs'; import {NavigationEnd, NavigationStart, Router} from '@angular/router'; @Injectable({ providedIn: 'root', }) export class AppInitializationService { baseElement: HTMLBaseElement; private targetSubstring = '/scm/smi/dist' private renderer: Renderer2; constructor(private rendererFactory: RendererFactory2) { this.renderer = this.rendererFactory.createRenderer(null, null); } setBaseUrl (router: Router, elm: ElementRef) { router.events.pipe(filter(event => event instanceof NavigationStart || event instanceof NavigationEnd)) .subscribe(async (routerEvent: any) => { if (await routerEvent instanceof NavigationStart) { // set base tag this.targetSubstring = elm.nativeElement.getAttribute('baseUrl'); this.setBaseHref(this.targetSubstring) } // remove <base /> after module loaded if (await routerEvent instanceof NavigationEnd) { this.removeBaseHref() } }); } setBaseHref(newUrl: string): void { const baseElement = this.renderer.createElement('base'); this.renderer.setAttribute(baseElement, 'href', newUrl); const headElement = document.querySelector('head'); if (headElement) { this.renderer.appendChild(headElement, baseElement); } } removeBaseHref() { const baseElements = document.querySelectorAll('base'); for (const baseElement of Array.from(baseElements)) { if (baseElement.href.indexOf(this.targetSubstring) > 0) { this.baseElement = baseElement } } if (this.baseElement) { this.baseElement.remove(); } } }
版权声明:本文由沐萱草的笔记发布,如需转载请注明出处。