Starting up Angular service with asynchronously loaded information

In my recent project, I have developed an interface along with two classes, A and B, that implement this interface. To handle the creation of objects of these classes based on the result of an asynchronous method, I have also created a factory service. This factory service, named SomeFactory, returns an object of either class A or B, depending on the result of an Observable of type boolean returned by the asynchronous method. However, I am facing a challenge in ensuring that the response from this method is obtained before an object of class A or B is created synchronously. How can I achieve this?

As I explore possible solutions, I am considering the limitations of using APP_INITIALIZER in this scenario. Since the described implementation resides in a library that will be imported into the main application, I am hesitant to introduce a dependency from the library to the main application. Here is a snippet of the SomeFactory code:

@Injectable({
  providedIn: 'root'
})
export class SomeFactory {

private static isEnabled : boolean = false;

constructor(private otherService: OtherService){}

loadState(){
 this.otherService.isEnabled().subscribe((isEnabled) => {
    SomeFactory.isEnabled = isEnabled
  })
}

  static create(): Interface {
    if(SomeFactory.isEnabled) {
      return new A()
    } else {
      return new B()
    }
  }
}

Answer №1

@Injectable({
  providedIn: 'root'
})
export class UniqueFactory {

private static isEnabled : boolean = false;
public instance;                             // it could be an instance of X or Y

constructor(private service: CustomService){}

loadData(): UniqueInterface{
    this.service.isEnabled().subscribe((isEnabled) => {
       UniqueFactory.isEnabled = isEnabled;

       // Setting isStopped to true for unsubscribe
       this.service.enable().unsubscribe(); // 

       return UniqueFactory.generateObject();
  });

}


public static generate(): UniqueInterface{

 // Setting isStopped to false initially
 if(!this.service.enable().isStopped){  
    return this.loadData();
 }else{
   return UniqueFactory.generateObject();
 }

}

private generateObject(): UniqueInterface{
    if(UniqueFactory.isEnabled) {
      return new X()
    } else {
      return new Y()
    }
  }
}

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

Angular2 form builder generating dynamic forms based on results of asynchronous calls

When creating my form, I encountered a challenge with passing the results of an asynchronous call to the form builder. This is what I have attempted: export class PerformInspectionPage implements OnInit { checklists: any; inspectionform: FormGroup; n ...

Create an entity with a field that holds a value type based on the value of another key field

Essentially, I am looking to create a customized "Pair" data type For example: type Pair<T extends Record<string, string | number>, K extends keyof T> = { field: K, value: T[K] } So, if we have: type Rabbit = { name: string, a ...

Updating the displayed data of an angular2-highcharts chart

I am facing an issue with rendering an empty chart initially and then updating it with data. The charts are rendered when the component is initialized and added through a list of chart options. Although the empty chart is successfully rendered, I am strugg ...

Testing Angular Components Using HostListener

I am looking to write unit tests for @HostListener, but I'm unsure of how to go about it since it's located on top of the component. Here is an example of the code: @HostListener('document:click', ['$event']) onDocumentClick ...

Switching Font Family Option for Selection Mat in Angular Material

I'm currently working on changing the font of the options inside mat-select ("In what city were you born", etc). After some experimentation, I found that by setting ViewEncapsulation to none (allowing styles from other files to bleed in), I am able t ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...

Encountering a 'blocked:other' error status while making a REST API call in my Angular application to retrieve data from the server

Example of the requested REST API URL: http://example.com/controller/api?bannerId=1&value=23 Encountering a browser error status: blocked:other while attempting to make an HTTP request to the server from the Angular application. ...

Error in ag-Grid CSV export feature displaying incorrect file names

Currently, I am coding in Typescript using Angular 2 along with ag-Grid (non-enterprise variant). An issue has arisen with the export feature of ag-Grid and I was wondering if someone could offer some assistance. If there is only one Grid on the form, ex ...

Ways to rename a sequelize property following a join operation

I am encountering a problem with sequelize ORM. The data returned after joining has a nested object: { "id": 1, "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4125342e2f26252e282220 ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

Injecting the OrderEntry context into the CartOutlets.ITEM_DETAILS outlet in Spartacus can be achieved by following these

Here is a question from a different source: Is there a way to access orderEntry while utilizing <ng-template [cxOutlet]="CartOutlets.ITEM_DETAILS"> </ng-template> placeholder from the cart-item component? It appears that without [c ...

Angular6 returns the result after subscribing to an HTTP POST request

Currently, I am in the process of learning angular and attempting to create a component that allows users to register through my web API. Within my component, the code on form submission looks like this: onSubmit(contactFormRef: NgForm) { const resu ...

Managing Errors in Angular: Utilizing Interceptors and Modal Pop-ups

I recently finished developing an Angular 5 application that effectively handles errors for each API call made. By utilizing the HttpClient, I am able to catch errors that occur post request sent to the server. The error interception occurs within a servic ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Effective ways of making mat-toolbar react to Angular modifications

For a while now, I've been struggling to create a simple header for the homepage of my web app using mat-toolbar. However, no matter what I try, I just can't seem to get it to display the way I want. Here's the code I've been working wi ...

Obtain data from a local JSON file using the http.get() method in Angular 2

I am attempting to utilize the http.get() method in Angular 2 to load a local JSON file. I followed a suggestion from Stack Overflow that involves modifying my app.module.ts: In this example, I have imported the HttpModule and the JsonModule from @angular ...

Disabling the experimental app directory feature in NextJs

I've been working on a real-life project and decided to test out the new App directory feature that comes with Next.js version 13. However, I encountered some issues such as images and fonts not loading properly. Now, I'm looking to opt out of th ...

What is the best way to handle a global path parameter in a Nest.js application?

Currently, I am in the process of constructing a rest API for a fully multi-tenant system using a single database and application. To achieve this, I have chosen NestJS as my framework of choice. My goal is to structure all modules based on the :tenantID t ...

How to Make an HTTP POST Request in Angular without Including Headers

How can I configure Angular (version 4.0.2) to send a minimal HTTP POST request? When I use the default code like this: import { Http, Response } from '@angular/http'; export class MyService { constructor(public http: Http) { this.http.pos ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...