Tips for delaying code execution in Angular until the service constructor has been called and completed

I have successfully stored the api_url in IndexedDB using NgxIndexedDBService. However, I am encountering an issue where I need to fetch the api_url before any service call is made. The problem arises when I attempt to call a service method from the constructor of a component, resulting in an exception because the api_url is still undefined while the subscribe method is fetching data from IndexedDB.

this.dbService.getByKey('CompanyInfo', 'test').subscribe((key: any) =>
{
    this.apiendpoint = key.API_URL;
});

Can anyone suggest an approach to delay the execution until the service constructor has completed? Alternatively, are there any other suggestions for handling this situation?

Answer â„–1

One way to ensure the apiendpoint is valid before using it is by wrapping it with a function that waits until the data is ready:

@Output() public apiendpointChanged: Subject<any> = new Subject();

this.dbService.getByKey('CompanyInfo', 'test').subscribe((key: any) =>
{
    this.apiendpoint = key.API_URL;
    this.apiendpointChanged.next(this.apiendpoint);
});

To create a function that checks if the data is already filled and returns it, or waits until the data is filled:

public getData(): Promise<any> {
    return new Promise((resolve, reject) => {
        try {
            if (this.apiendpoint) {
                resolve(this.apiendpoint)
            } else {
                const subs = this.apiendpointChanged.subscribe(data => {
                    resolve(this.apiendpoint)
                    subs.unsubscribe();
                })
            }
        } catch (error) {
            reject(error)
        }
    })
}

When you need the value of apiendpoint, simply add this call:

await getData();

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

Combining an array into another array using the same key in JavaScript

My goal is to merge the array itself and transform it into a more meaningful array array = [ {item: 'pen', madeIn: 'US', color: 'blue'}, {item: 'pen', madeIn: 'US', color: 'white'}, {item: ' ...

Whenever I update the values in my input using the ngModel attribute, all of my arrays stored in an object also get updated

I am currently working with a table on the frontend. <table class="table table-hover"> <thead> <tr> <th> Account Entry Number </th> <th> ...

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

Encountering error codes TS1005 and TS1109 while trying to run an Angular 6 project

Having difficulty starting my Angular 6 app due to this specific error. Is there a solution available? ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected. node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ...

Steps for setting up Angular 5 on your system

My current project requires Angular 5, but with the recent release of Angular 7, I'm unsure how to set up Angular 5 on my computer. I had transitioned from Angular 6 a few months ago. Do I need to uninstall the latest version to work with Angular 5? ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

Eliminate the loading screen in Ionic 2

Within my app, there is a button that triggers the opening of WhatsApp and sends a sound. Attached to this button is a method that creates an Ionic loading component when clicked. The issue I am facing lies with the "loading.dismiss()" function. I want the ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Exploring Objects within an Array in Ionic 2 and AngularJS 2

I am currently working on displaying reviews obtained from a Laravel API, showcasing feedback on various meals. The goal is to create a slideshow of review messages along with additional data as presented in the array of Objects below: { "2": { ...

Troubleshooting npm installation issues with Angular 2 Quickstart guide (URL: https://angular.io/docs/js/latest/quickstart.html)

I am currently facing issues when trying to set up Angular 2 on my Ubuntu 15.10 system. Despite multiple attempts, the installation fails and I receive error messages. Even after attempting to install Angular 2 using the npm package command sudo npm insta ...

What is the method to retrieve a chat that has been ended with JavaScript SDK?

Whenever I attempt to retrieve a closed Twilio Conversation on the frontend using the JS SDK, I encounter a "Not found" error. Can closed conversations be fetched? My objective is to enable users to close a conversation while still having access to the m ...

TypeScript modules located within the node_modules directory and then deployed within the wwwroot folder

Implementing this in an ASP.NET Core 2.x web application should have been straightforward considering it's a standard pattern. However, I seem to be doing something very wrong. Here is the folder structure that I am working with: projectRoot ├─â ...

Executing numerous $http calls in Ionic2

I am curious about the possibility of making multiple requests in Angular: Suppose I start $http request 1, and when it finishes, attempt to call $http request 2. How can I achieve this? For instance, initiating $http request 1 followed by $http request ...

Leveraging async/await in Firebase functions along with the once() method

Recently diving into the world of TypeScript, I've been navigating my way through with relative ease. However, I've encountered a perplexing issue while working with async/await. The problem lies within this code snippet - the 'await' ...

Building a custom menu component in AngularCli using primeNG - a step-by-step guide

Just starting out with angular 2, I've successfully created a button and calendar component using NGPrime. However, I've hit a roadblock with the menu component. Following these instructions, I encountered the following error https://i.sstatic.n ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Tips for accessing data in Angular 2

When utilizing the post method, the following code is used in the ts file: viewt(testid) { $('#myModal22').modal('show'); var param2 = { testid:testid, } this.service.get_tquestion(param2).subscribe(data => { ...

Update the input for a component within the ngOnChanges method, and ensure that the OnPush change

I've encountered an issue with my Angular 6 application: The Dilemma Imagine I have two components: parent and child. The child component has two inputs. When one input changes, the child emits something to the parent within the ngOnChanges() lifec ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...