The issue with APP_INITIALIZER is that it fails to resolve promises before moving on to other

I can't seem to figure out what's missing here. I hope it's just a minor issue.

The problem I'm facing is that the APP_INITIALIZER isn't resolving completely.

In my code, I have two services: AppSettingsService and SomethingService. I've introduced a new injectable token called "API_BASE_URL" that I want to inject into SomethingService. AppSettingsService has a method named setup() which sets the string "test" within a Promise. My intention is for this promise to be resolved before setting API_BASE_URL. However, it appears that the code doesn't want to wait for it!

I've included a sandbox link:

Sandbox

If you open the console and observe, these are the steps it follows:

"Executing promise" (this is as expected) "Getting test string too early" (I would expect this after the promise resolves) "undefined" (this occurs because I'm trying to print appSettings.test but it hasn't been set yet due to the unresolved Promise) "Resolving promise" (this happens shortly thereafter due to the setTimeout())

Any assistance would be greatly appreciated!

Answer №1

Each of the `useFactory` sections within the providers is missing a return statement. The corrected code can be found below:

import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { AppSettingsService } from './app-settings.service';
import { API_BASE_URL } from './something.service';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    AppSettingsService,
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [AppSettingsService],
      useFactory: (appSettingsService: AppSettingsService) => {
        return () => {
          return appSettingsService.setup();
        };
      },
    },
    {
      provide: API_BASE_URL,
      deps: [AppSettingsService],
      useFactory: (appSettingsService: AppSettingsService) => {
        console.log('Getting test string too early');
        console.log(appSettingsService.test);
        return appSettingsService.test;
      },
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

View on CodeSandbox

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

I want to swiftly display the API response using console.log in Angular 8

My current setup involves using a service to log the response from a News API like this: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) exp ...

Before users can apply any filters, all items must be loaded into an Observable<Hero[]> array

Is there a way to modify the Angular 2 Tour of Heroes search component so that it displays all items on page load (showing all Heroes) and then makes a new request to get filtered results only when a filter is provided? import { Component, OnInit } from & ...

The predicament with arranging arrays

I'm working with an array that looks like this: [ { "TaskID": 303, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { "TaskID": 304, ...

Encountered an error of 'No overload matches this call' while configuring ContextApi alongside useReducer with Typescript

I am currently setting up ContextApi and useReducer with typescript. I am encountering an error with my "issuesInitialState" variable in useReducer, where I receive the following message: No overload matches this call. Overload 1 of 5, '(reducer: ({ ...

Using either AngularJS's simple .then method or the $q service to handle asynchronous requests

I'm trying to understand the distinction between AngularJS $q service and simply using .then() after an asynchronous request. For example, using .then(): function InboxService($http) { this.getEmails = function getEmails() { return $http.get(& ...

What is the best way to obtain an attribute name that is reminiscent of Function.name?

My objective is to securely type an attribute. For example, I have an object: const identity = { address: "Jackie" }; At some point, I will rename the address key to something else, like street_address. This is how it is currently implemented ...

Refine an Array by applying multiple filters

Here is a simple JSON array that I have: const personList = [ { id: 1, name: "Phil" }, { id: 2, name: "Bren" }, { id: 3, name: "Francis Underwood" }, { id: 4, name: "Claire Underwood" }, { id: 5, name: "Ricky Underw ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Experiencing the error message "delete(...).then(...).error is not a function" while attempting to remove a file from Firebase storage using AngularFire and TypeScript

I'm trying to implement the code snippet from Firebase documentation to delete a file and then upload a new image in the same directory on Firebase Storage. However, I keep encountering an error message saying "delete(...).then(...).error is not a fun ...

Ensuring the correctness of environment variables in Next.js using Zod

After spending the entire day trying to figure it out, I realize that the solution may be simpler than expected. I am currently using the well-known zod library to validate my environment variables and transform data. However, I keep encountering a persis ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: It appears that validate and formSubmit are being recognized as unused variables by typescript, resulting in the following jsx error: ...

Using Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

The Bootstrap carousel is experiencing compatibility issues with Angular 7 and is currently not functioning properly

I'm currently using the bootstrap multi carousel, and it works perfectly without a loop. However, when I try to implement it dynamically using an ngFor loop, it doesn't function as expected. Instead of sliding with multiple images, it just displa ...

Error message: The value of ngIf has been altered after it has been checked

I am encountering the ngIf value changed error in my code and I'm unsure of the correct solution. Below is the HTML snippet causing the issue: <div *ngIf="currentVlaue"> <div class="section-body"> <div cla ...

What is the process for parameterizing a tuple in coding?

In my scenario, I have a tuple with interrelated types. Specifically, it involves an extractor function that retrieves a value, which is then used as input for another function. What I envision conceptually looks like this code snippet, although it does n ...

Exporting the interface for the state of the redux store

After setting up a redux module, I have organized the following files: //state.tsx export default interface State { readonly user: any; readonly isLoggedIn: boolean; } //types.tsx export default { REQUEST: 'authentication/REQUEST', SUC ...

Gaining entry to a static member of an exported class in a module

I am facing an issue with my Typescript code snippet. The code is as follows: module MyModule { export class MyClass { static MyStaticMember : string; } } My requirement is to access this code from a separate file after compilation. I tri ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...