refactor: UrlService auf Lazy Loading umgestellt

This commit is contained in:
Developer 02 2024-07-23 13:13:32 +02:00
parent f502a47090
commit b880a3245d
4 changed files with 30 additions and 17 deletions

View File

@ -1,4 +1,4 @@
import { ApplicationConfig } from '@angular/core';
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
@ -6,8 +6,7 @@ import { provideAnimationsAsync } from '@angular/platform-browser/animations/asy
import { provideHttpClient, withFetch } from '@angular/common/http';
import { APP_BASE_HREF } from '@angular/common';
import { UrlService } from './services/url.service';
import { CONFIG } from './tokens';
import { ConfigService } from './services/config.service';
import { API_URL } from './tokens';
export const appConfig: ApplicationConfig = {
providers: [
@ -19,11 +18,16 @@ export const appConfig: ApplicationConfig = {
provide: APP_BASE_HREF,
useFactory: (urlService: UrlService) => urlService.getBaseHref(),
deps: [UrlService]
},
{
provide: API_URL,
useFactory: (urlService: UrlService) => urlService.getApiUrl(),
deps: [UrlService]
},
{
provide: CONFIG,
useFactory: async(configService: ConfigService) => await configService.getConfig(),
deps: [ConfigService]
provide: API_URL,
useFactory: (urlService: UrlService) => urlService.getApiUrl(),
deps: [UrlService]
}
]
};

View File

@ -7,21 +7,30 @@ import { env } from '../../environments/environment';
providedIn: 'root'
})
export class UrlService {
document: Document;
meta: Meta;
constructor() {
this.document = inject(DOCUMENT)
this.meta = inject(Meta)
}
private loaded:boolean = false;
private base_href: any;
private api_url: any;
constructor(@Inject(DOCUMENT) private document: Document, @Inject(Meta) private meta: Meta) {}
private lazyLoad(){
if(this.loaded)
return;
this.base_href = this.document!.querySelector('base')?.getAttribute('href') || '/';
this.api_url = (this.meta!.getTag('name="api-url"')?.content ?? env.default_api_url);
this.loaded = true;
}
getBaseHref(): string {
const baseElement = this.document.querySelector('base');
return baseElement?.getAttribute('href') || '/';
this.lazyLoad()
return this.base_href;
}
getApiUrl(route: string = ""): string {
return env.api_url + route;
this.lazyLoad()
return this.api_url + route;
}
readonly apiRoute = {

View File

@ -1,3 +1,3 @@
import { InjectionToken } from '@angular/core';
export const CONFIG = new InjectionToken<string>('CONFIG');
export const API_URL = new InjectionToken<string>('API_URL');

View File

@ -1,6 +1,6 @@
export const env = {
production: false,
api_url: "/api",
default_api_url: "/api",
routes: {
user: "/user",
group: "/group",