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

Tips on how to restore the default value for a select dropdown in Angular 2

Is there a way to reset a select element back to its first option when the clear button is clicked? I have a select with the first option serving as a placeholder, but I'm having trouble resetting it. <select class="form-control" aria-placeholder= ...

Tips for making a dynamic link button using Angular

I am currently working on creating responsive buttons that will navigate to specific pages using Angular routing. Here is my routing configuration: const routes: Routes = [ { path: 'home', component: HomeComponent}, { path: ' ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Transitioning a codebase from @angular-builders/custom-webpack to NX for project optimization

I need help migrating my Angular project from using "@angular-builders/custom-webpack" build targets to transitioning to an integrated NX monorepo. When I run the command npx nx@latest init --integrated, I receive the following warning: Unsupported build ...

Intercepting and manipulating HTTP response headers using Angular's HTTP

After sending a post request for logging in, the response includes a token in the header called Set-Auth. How can I extract and utilize this token in subsequent request headers? login() { if (this.loginForm.invalid) { this.messageService.warnin ...

Combining ngModel and ngClass in Angular: a comprehensive guide

I have implemented the following code in Angular 6 using Visual Studio Code <div [ngClass]="{'disabled': isReadOnly}"> <label class="switch"> <input type="checkbox" name="Gender" ...

Steps for associating ngclass with an observant value

Can you bind to an Observable<enum> like this in Angular? <a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" /> or <a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" /> where the observable is named mapTool ...

Converting SQL COUNT query to angularfire2: A guide on translating Firebase / angularfire2

In my firebase database, I have the following structure: "users" : { "USER1_ID" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41343224337001393939396f222e2c">[email protected]</a>", ...

The upcoming construction of 'pages/404' page will not permit the use of getInitialProps or getServerSideProps, however, these methods are not already implemented in my code

Despite my efforts to search for a solution, I have not found anyone facing the same issue as me. When I execute next build, an error occurs stating that I cannot use getInitalProps/getServerSideProps, even though these methods are not used in my 404.tsx f ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

Developing and employing Services in Angular 2

Having some trouble with Angular2 as I explore it for the first time, specifically in creating and using a service. I've set up a data service like this: import {Injectable} from 'angular2/core'; import {recentActivity} from './app/com ...

Implementing Styled API in TypeScript with props: A Comprehensive Guide

I'm currently working on styling a component using the new styled API, not to be confused with StyleComponents. const FixedWidthCell = styled(TableCell)((props: { width: number }) => ({ width: props.width || 20, textAlign: "center", })) The i ...

Is there a way to unselect a button in Angular?

I have a set of buttons representing different categories. When I click on a button, it displays a card with relevant information. <app-category-button [label]='category.name' [isSelected]='category.id === (selectedCategoryId$ | asy ...

Implementing Authorization keys in Angular's Swagger UI using code

I am currently in the process of integrating swagger ui into an Angular 7 application. Utilizing the npm package swagger-ui 3.37, the API documentation is structured with swagger 2.0. The integration works smoothly when authorization is not required within ...

Transferring the web application context to an Angular2 service

In my project, I am attempting to pass a variable named _contextPath from a Javascript evaluated variable in a JSP file located in the folder structure shown below. The goal is to make this _contextPath variable available in a Typescript Service called job ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...

Utilize Jasmine to spy on an inner function and return a mock value from the last function call

I'm currently working on a Jasmine test where I have an object structure like this: class User { public getData(): void { return { getPersonalInfo: () => { ... } } } } Typically, I would access it as ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...