File

src/lib/config-loader.service.ts

Index

Properties
Methods

Constructor

constructor(http: HttpClient)
Parameters :
Name Type Optional
http HttpClient No

Methods

Public Async load$
load$(url: string)
Type parameters :
  • T
Parameters :
Name Type Optional
url string No
Returns : Promise<T>

Properties

Public Readonly configLoading
Default value : new Map<string, Observable<any>>()
Public Readonly configs
Default value : new Map<string, any>()
Public Readonly http
Type : HttpClient
Decorators :
@Inject(HttpClient)
import {
  Inject,
  Injectable,
} from '@angular/core';
import {
  firstValueFrom,
  Observable,
} from 'rxjs';
import { HttpClient } from '@angular/common/http';
import {
  finalize,
  share,
} from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class ConfigLoaderService {
  public readonly configs = new Map<string, any>();

  public readonly configLoading = new Map<string, Observable<any>>();

  constructor(
    @Inject(HttpClient)
    public readonly http: HttpClient,
  ) {
  }

  public async load$<T = any>(url: string): Promise<T> {
    if (this.configs.has(url)) {
      return this.configs.get(url);
    }

    if (this.configLoading.has(url)) {
      return this.configLoading.get(url)!.toPromise();
    }

    const loading$ = this.http.get<T>(url).pipe(
      finalize(() => this.configLoading.delete(url)),
      share(),
    );

    this.configLoading.set(url, loading$);

    return firstValueFrom(loading$);
  }
}

results matching ""

    No results matching ""