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

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

Transferring data between components in React by passing parameters through Links

When calling another component like <A x={y}/>, we can then access props.x inside component A. However, in the case of calling EditCertificate, the id needs to be passed to the component. I am using a Link here and struggling to pass the id successf ...

Tips for making a oneOf field nullable using TypeScript and AJV

A field named platform exists in my code, and it can hold either a string or an array of strings (string[]). The field can also be nullable or undefined if not passed as input. TypeScript Interface export interface IEntityLeaderboardQuery { rank: stri ...

Navigating in Angular 2.0.0-rc1 with routes and setting a default route using use

Is it true that "useAsDefault" has been removed in angular2.0.0-rc1? Any suggestions for a workaround? I noticed in the Angular documentation they are using the OnInit method... Do subroutes still function with the /... notation? Thanks ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

The `role` property is not recognized in the type `User | AdapterUser` within NextAuth

In my attempt to develop a NextJS application integrated with NextAuth, I am facing an error in my [...nextauth].ts file while setting up the callbacks: Type error: Property 'role' does not exist on type 'User | AdapterUser'. Property ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

TS2365: The '!== 'operator is not compatible with the types ""("" and "")""

function myFunction(identifier: string) { identifier = "("; }; let identifier: string = ")"; if (identifier !== '(') throw "Expected '(' in function"; myFunction(identifier); if (identifier !== ')') throw "Expected &a ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

Angular and Firestore, when combined, present a unique challenge as the queries

After upgrading the code of an outdated project to the latest versions of Angular and RxJs, I made every effort to update the code as thoroughly as possible. Here is a link to my previous code However, I am now encountering the issue of receiving undefin ...

Finding the common dates between two date arrays in Node.js

Looking for help with correctly intersecting matrices while working in nodejs? Trying to compare two arrays to find common elements, also known as an "array intersection." This seems to be a common question, and despite trying various solutions mentioned o ...

Error message TS2339 in Typescript: The property '__super__' is not found on the type '($element: any, options: any) => any'

Having trouble with Javascript code inside typescript. $.fn.select2.amd.require([ 'select2/data/array', 'select2/utils' ], function (ArrayData, Utils) { /* tslint:disable */ function CustomData ($element, opti ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Tips for changing the name of a directory in an Angular 6 application

Looking for guidance on renaming a folder in an Angular 6 project's components directory. Is there a safe way to do this without causing any issues, or is it as simple as just changing the name of the folder? Using Visual Studio Code as my IDE. ...

Instructions on how to link a button to display and conceal content when clicked

I'm working on a project with a list of headers and paragraphs, and I want to create a button that will show or hide the paragraph when clicked. However, I'm struggling with getting the paragraph to hide again when the button is clicked a second ...

Utilizing Angular 2+ to effectively manipulate the HTML Document Object Model with JavaScript in order to execute scripts

I'm facing an issue with inserting a script into my Angular project that has a specific format. <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js"> { "width": "510", "height": "600", "impo ...

When executing the "node app.js" command, the <app-root> element appears empty in the browser

After creating an Angular 7 application with the Angular CLI and adding my express server, I encountered a strange issue. When starting my app with the command "node server/app.js", the browser displayed <app-root></app-root> in the "Elements" ...

Encountering a Problem with Angular 2 Directive *ng-for

Recently started experimenting with the beta version of Angular 2.0 and encountered an error stating "angular is not defined" while trying to add directive: [angular.ngFor]. If you want to take a look, here is the Plunker URL: http://plnkr.co/edit/ULHddLR ...

The beauty of crafting intricate forms with Angular's reactive nested

In my Angular project, I am exploring the concept of nesting multiple reactive forms within different components. For instance, I have a component called NameDescComponent that includes a form with two inputs - one for name and one for description, along ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...