Could an OpaqueToken be assigned using an observable?

I am attempting to establish an opaque token in the providers using an observable. The purpose behind this is that I am retrieving the value through the Http provider (from an external JSON file).

This is my current approach:

    {
        provide: SOME_OPAQUE_TOKEN,
        useFactory: (configService: ConfigService) => {
            configService.getPath('campaigns')
                .subscribe((res) => {
                    ???
                });
        },
        deps: [ConfigService],
    },

It's evident that this method will not work, so I'm curious if there is a solution to tackle this issue?

Is it feasible to construct a service using useFactory where one of the parameters is fetched asynchronously?

Does such a possibility exist?

Edit: Solution utilizing APP_INITIALIZER

In AppModule:

{
  provide: APP_INITIALIZER,
  useFactory: (configService: ConfigService) => () => configService.load(),
  multi: true,
  deps: [ConfigService, Http],
},

In ConfigService load():

public load(): Promise<Configuration> {
    let promise =
        this.http
            .get('config.json')
            .map(m => m.json())
            .toPromise();

    promise
        .then(config => this.appConfig = config);

    return promise;
}

Once the appConfig is set, we can utilize it to define the OpaqueToken:


{
        provide: BASE_PATH,
        useFactory: (configService: ConfigService) => configService.appConfig.basePath, deps: [ConfigService],
    },

Answer №1

APP_INITIALIZER is a little-known feature that allows for resolving app dependencies asynchronously.

An initializer, in this context, refers to a function that can return either a promise for asynchronous initialization or any other value for synchronous initialization. Since APP_INITIALIZER supports multiple providers, several initializers can be defined and executed concurrently. You can find the implementation details here.

To define an initializer as a provider in a module:

{
  provide: APP_INITIALIZER,
  useFactory: (...deps...) => () => promise,
  deps: [...deps...],
  multi: true
}

Alternatively, for an initializer with no dependencies:

{
  provide: APP_INITIALIZER,
  useValue: () => promise,
  multi: true
}

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

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

Encountered an error in Angular Universal + PWA stating: { Error: Uncaught (in promise): Error: Unable to find a match for the routes. URL Segment: 'ngsw_worker.es6.js

I have successfully set up a universal and PWA app. Is there a solution to resolve this issue? You can check out a DEMO (the first push :) ) here SERVER SIDE CONSOLE ERROR { Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: &ap ...

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

Display captions on react-player videos using an .srt file

Currently, I am working on a React/Typescript project with Next.js. A key feature of this project is a modal that utilizes 'react-player' to display videos. While the video and modal are functioning as intended, I am looking to incorporate capti ...

In Angular 10, the custom CSS URL is loading after the standard styles.css file

Below is the configuration from my angular.json file: "options": { "outputPath": "dist/example", "index": "src/index.html", "main": "src/main.ts", ...

Enhancing Visual Studio 2017 with Docker Compatibility for Angular Applications

What is preventing the angular support from being available in VS 2017? Is there a missing component that is needed? https://i.stack.imgur.com/asJhO.png ...

Issue with TranslateModule Configuration malfunctioning

I have put together a file specifically for managing ngx-translate configuration: import { Http } from '@angular/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModu ...

Experiencing template parsing errors in Angular 2+ unit tests with Karma and Jasmine

Encountering problems with running Angular tests on certain components, even though they function properly in production. Seeing the following error message: Failed: Template parse errors: 'app-date-picker' is not a recognized element: 1. Ensure ...

The error that has occurred is: `TypeError: The object on the right side of the 'instanceof' keyword is

Testing my function that verifies if a variable is an instance of a specific type and performs an action has been successful. I conduct the verification using the following code: myCheckingFunction = () => { if (target instanceof H.map.Marker) { ... ...

Use a function on values that have corresponding keys in a separate array

I am working with a form.value object that looks like this: form.value = { "to_date": "2019-03-21T05:00:00.000Z", "from_date": "2019-03-13T05:00:00.000Z", "is_form": "" "errors":"" } Additionally, I have an array called filterArray: filterArray ...

Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply. The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then callin ...

The Angular 4 proxy configuration file is not properly directing to the specified target destination; instead, it is redirecting to localhost:4200

I'm having trouble with my Angular 4 proxy configuration file - it's not redirecting to the target I specified and instead is redirecting to <http://localhost:4200>. ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

The sole coding platform that fails to acknowledge the "ng" command is Visual Studio Code

Many users have encountered issues where the computer does not recognize 'ng,' but my problem differs from that. Interestingly, every software with a command shell recognizes 'ng' except for VS Code. IntelliJ? Works fine. Git bash? N ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

What are some ways to customize the appearance of gridlines in a PrimeNG p-table?

Currently, I am attempting to eliminate or modify the color of the gridlines on my p-table. I have gone through the code in the browser to locate the specific element responsible for these lines, but unfortunately, it has eluded me thus far. Even after t ...