Home > Enterprise >  How to load config file from http request on initialization of library in Angular
How to load config file from http request on initialization of library in Angular

Time:09-08

i am trying to solve race condition in our application. We have base urls stored in extarnal config file and every request needs to access this file.

Currently we are calling request for this file in constructor.

// getting url from file
// getEnv uses share() so calling it multiple times is ok it just need to be loaded before calling any request to BE
constructor(private http: HttpClient, private envService: EnvironmentService) {
    this.envService.getEnv('baseUrl').subscribe({
      next: (apiUrl) => {
        this.apiUrlBase = `${apiUrl}${someSufix}`;
      },
    });
  }

  possibility that apiUrlBase is not yet inicialized and request is invalid
  get(x: string): Observable<sameData> {
    return this.http.get<someData>(`${this.apiUrlBase}${x}`);
  }

Is there better way to do this instead of this everywhere?

// getEnv uses .pipe(share())
this.environmentService.getEnv('baseUrl').pipe(
  mergeMap(apiUrlBase => this.http.get<someData>(`${this.apiUrlBase}${x}`)
)

We are using angular 13 and this is inside of our library. I am thinking about calling getEnv in library constructor but thanks for any suggestion.

CodePudding user response:

Read this doc

You can make http call before your application load and then save the urls in any service or local storage and use it as needed.

  • Related