Verify two asynchronous boolean variables and trigger a function if both conditions are met

Is there a way to enhance the rendering process so that the renderFilters() method is only called when both variables are true:

These two variables are loaded asynchronously through 2 API methods:

//getManager() 
this.isLoadingManager = true;
//getPdiPOrganization()
this.isLoadingPdiOrganization = true;

promiseRender() {
        let interval = setInterval(() => {
            if (this.isLoadingManager && this.isLoadingPdiOrganization) {
                clearInterval(interval);
                this.renderFilters();
            } else {
                setTimeout(() => {
                    clearInterval(interval);
                    this.renderFilters();
                }, 5000)
            }
        }, 500);
    }

The issue is that it's too slow... it triggers long after the APIs are called... Perhaps Angular has a built-in feature for this, any better ideas...

const observable = forkJoin({
        loading1:this.isLoadingManager,
        loading2:this.isLoadingPdiOrganization
      });
      observable.subscribe({
        next: (results) => {
            const obs1Val = results[0];
            const obs2Val = results[1];
            if (obs1Val && obs2Val) {
                this.renderFilters();
            }
          }
      })

Alternatively:

   const myObservable = Observable.of(this.isLoadingManager && this.isLoadingPdiOrganization);
                const myObserver = {
                   next: (result: Boolean) => this.renderFilters(),
                };
                myObserver.next(true);
                myObservable.subscribe(myObserver);

Implementing the methods:

 getManager() {
            if (this.fromAdminPage && localStorage.getItem('_receivers_pdi')) {
                this.meetingService.getIsManager()
                    .subscribe(res => {
                        this.showPdiToastNotification = res;
                        this.isLoadingManager = true;
                    });
            }
     }

getPdiPOrganization() {

        const url = this.publicEndpoint ? 'current/organization/pdi/configuration' : 'api/current/organization/pdi/configuration';

        const requestOptions = {
            params: new CustomHttpParams({ isPublicTokenUrl: this.publicEndpoint })
        };

        this.http.get<any>(url, requestOptions).subscribe(resp => {
            this.isLoadingPdiOrganization = true;
            this.pdiOrgConfig = resp || {};
            this.updatePdiReferenceType(this.pdiOrgConfig);
        });

    }

Answer №1

To handle subscribing to two observables simultaneously, you can utilize the forkjoin method. It's advisable to make use of RxJs operators in scenarios like this. For more information on using forkJoin, check out this link.

forkJoin([obs1, obs2]).subscribe({
  next: (results) => {
    const obs1Val = results[0];
    const obs2Val = results[1];
    if (obs1Val && obs2Val) {
      this.renderFilters();
    }
  }
});

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

Solving issues with malfunctioning Angular Materials

I'm facing an issue with using angular materials in my angular application. No matter what I try, they just don't seem to work. After researching the problem online, I came across many similar cases where the solution was to "import the ...

Customized Grafana dashboard with scripted elements

I'm running into an issue while using grafana with graphite data. When I attempt to parse the data, I encounter an error due to the server not providing a JSON response. I am experimenting with scripted dashboards and utilizing the script found here: ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Optimal method for displaying the children component twice in Next.js

In order to create an infinite slider, I had to duplicate the data within my component. The data consists of an array containing a maximum of 20 items, each with an image. The slider is functioning perfectly. Although it may seem unconventional, it was n ...

Utilizing Javascript to create interactive images in HTML

Is there a way for JavaScript to open the current image in a new WINDOW when an ONCLICK event occurs? <script> function imgWindow() { window.open("image") } </script> HTML <img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" ...

Trouble with the 'uppercase' package in Node.js: Receiving ERR_REQUIRE_ESM error while utilizing the require() function

I am encountering a problem with the 'upper-case' module while developing my Node.js application. My intention is to utilize the upper-case module to convert a string to uppercase, but I'm running into difficulties involving ESM and require( ...

What is the best way to handle a large number of nested AJAX GET requests?

My task involves making numerous AJAX GET requests, which must be nested because each request depends on variables from the response of the previous one. Although I was able to make multiple requests with the example below, it becomes impractical when dea ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first. HTML: <ul> <li *ngFor="let reply of message_show.messages"> ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

Unusual Behavior of *ngIf and jQuery in Angular 5: A curious case

I'm encountering a strange issue when using the expand-collapse feature of Bootstrap 4 with *ngIf for expansion and collapse. I noticed that the jQuery doesn't work when *ngIf is used, but it works fine when *ngIf is removed. HTML: <div cla ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

Having trouble terminating the session with the authentication provider SSO on Node JS

I'm struggling with ending the session properly when a user makes a request to my /logout endpoint. I want to clear the session and require the user to log in again via SSO. Currently, after an initial login, I remain logged in without needing to re-e ...

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

Dividing the array into distinct subarray groups

I am working with a JavaScript array that contains strings, like this: let a = ["a", "a", "a", "b", "c", "c", "b", "b", "b", "d", "d", "e&quo ...

Is there a way to run Angular code without having to bootstrap it?

Typical manual bootstrapping examples often use the same pattern: angular.module('myApp', []); angular.bootstrap(document, ['myApp']); However, I only need Angular to trigger a popup using the ui-bootstrap module. The closest solutio ...

The setTimeout function fails to behave as intended when used in conjunction with synchronous ajax

Within my code, I have a function that is being invoked multiple times due to iterating through an array of length n and creating 'Plants' with synchronous ajax calls. These calls involve querying the Google Maps API, so it is crucial to throttle ...

Is there a way to modify the color of a specific section of a font icon?

Currently, I am in the process of implementing an upvote button using fa fa signs. However, I have encountered an issue where the background color of the up vote button is bleeding outside of the sign (possibly due to padding on the icon), and I am strivin ...

Issues are being faced with the execution of JavaScript on Heroku when using Rails 3.1

After upgrading a Rails 3.0 app to 3.1 on Heroku running on the cedar stack, everything seemed fine except for one major issue - the app's JavaScript wouldn't run. Despite the application.js file being compiled and accessible at myapp.com/assets/ ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...