Initialize app by calling Angular 13 service loader

I'm currently using Angular 13 and attempting to connect with Angular's bootstrapping phase through the APP_INITIALIZER token. I need to create an Angular service that manages the retrieval of our remote configuration. However, I've run into an issue where promises are no longer supported and have been deprecated. Can someone provide guidance on how to refactor the loadAppConfig() method since APP_INITIALIZER only works with promises? Any assistance would be greatly appreciated.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppConfigService {
  private appConfig;

  constructor(private http: HttpClient) { }

  loadAppConfig() {
    return this.http.get('/assets/data/appConfig.json')
      .toPromise()
      .then(data => {
        this.appConfig = data;
      });
  }

  getConfig() {
    return this.appConfig;
  }
}

Answer №1

When it comes to handling promises and observables, the APP_INITIALIZER in Angular is a versatile tool. According to the documentation provided at https://angular.io/api/core/APP_INITIALIZER,

"If any of these functions returns a Promise or an Observable,"

An example demonstrating the use of an observable can be seen below:

function initializeAppFactory(httpClient: HttpClient): () => Observable<any> {
 return () => httpClient.get("https://someUrl.com/api/user")
   .pipe(
      tap(user => { ... })
   );
}

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: initializeAppFactory,
    deps: [HttpClient],
    multi: true
  }]
})
export class AppModule {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method to remove oneself from ThunkAction?

Is there a way to retrieve reference for unsubscribing from a ThunkAction like the following: export const fetchSomeData = () => async (dispatch: Dispatch, getState: GetState) => { let unsubscribeUserAuth: UnsubscribeUserAuth | null = null; let u ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

After inputting the required parameters for the React onChange event, an unexpected error persists despite my efforts

I'm struggling with a bug in my React / typescript code. I have created a custom Input component that includes an 'onChange' property as described below: onChange?: (value?: string, event?: React.ChangeEvent<any>) => void; Here is ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...

Tips for transforming numerous observables into a single observable that emits a single value upon completion of all source observables

When submitting a form, I need to call an API method multiple times using Angular's HttpClient. Each call adds a specific item into another entity, as our backend does not provide a batch-add method. Therefore, I have to make individual calls for each ...

How do I retrieve the data returned from the component.ts file in Angular Material's MatTableModule when it is not directly inside the mat-table in the template?

I'm currently working on an Angular 5 project where I have integrated a table to display data using MatTableModule from angular material. This specific inquiry consists of two parts. Within my project, there is a service that sends a GET request to t ...

Challenge when providing particular strings in Typescript

Something seems to be wrong with the str variable on line number 15. I would have expected the Typescript compiler to understand that str will only ever have the values 'foo' or 'bar' import { useEffect } from 'react' type Ty ...

Encountering a TypeError while attempting to retrieve an instance of AsyncLocalStorage

In order to access the instance of AsyncLocalStorage globally across different modules in my Express application, I have implemented a Singleton class to hold the instance of ALS. However, I am wondering if there might be a more efficient way to achieve th ...

viewing state data using reactjs

In an attempt to incorporate react context into one of my projects, I'm facing a challenge. Specifically, I want to showcase the state information once the state is modified, i.e., when the confirmFavourites function is invoked. export class AppProvi ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

Utilizing .js file alongside declaration files .d.ts in Angular: A guide

I am facing an issue with my Angular 7 app where I need to include some typed JS constants from outside of the project. These constants are essential for the AngularJS app and need to be kept in a separate js file. I have defined a new path in the tsconfig ...

Having trouble accessing HikVision Web SDK functions in Angular 17

First and foremost, this concerns the HikVision cameras specifically. Because the SDK is compiled to plain JavaScript (with jQuery included), I had to import the JS files in angular.json and use declare in the component TS file (in this instance, camera.c ...

Reading text files line by line in TypeScript using Angular framework is a valuable skill to have

Struggling with reading text files line by line? While console.log(file) may work, it doesn't allow for processing each individual line. Here's my approach: In api.service.ts, I've implemented a function to fetch the file from the server: ...

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Searching for the correct navigation menu path using Angular 5's query functionality

Struggling to retrieve the Angular path query from the navigation menu. Every attempt I make with the code below results in undefined or null: this.route.paramMap.subscribe(params => this.Name = params.get('name') ); Here ...

Token does not contain the necessary claim nbf (not before) for access while utilizing Firebase Microsoft Sign-in to retrieve data from MicrosoftGraph

I currently have a mobile application structured with Angular on the front-end and a Node.js server on the backend. We have successfully integrated Google Cloud's Identity Providers for users to sign in using Google and/or Microsoft accounts. While ...

Issue: The "target" key is deprecated and will not be recognized in next.config.js anymore

WARNING - The next.config.js file contains invalid options: The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devInd ...

Why isn't TypeScript acknowledging my string literal declaration?

Below is the code snippet I am working with: type Timeframe = "morning" | "afternoon" | "evening"; let myTimeframe: Timeframe = "morning"; const someValue: any = {time: "incorrect"}; myTimeframe = someValue.time; console.log(myTimeframe); I want myTim ...

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...