Angular 2 - Ensuring service executes only when boolean condition is met

I am currently dealing with a navigation menu that utilizes the ng2-page-scroll module.

When scrolling through the page using hashtag links, I encountered an issue. If I navigate across routes, there is a delay in loading the data. As a result, the service initially scrolls to my desired section, but by the time all the data loads, the section is no longer visible on the screen. This requires manual scrolling to reach the intended section, rendering the entire menu ineffective.

To address this issue, I have implemented EventEmitters in all sections to set boolean values in the "scrollable" page, which works well. However, I am unsure of how to wait for the allDataLoaded boolean to become true.

In an attempt to solve this, I tried using promises.

This is the current state of my code.

HTML for the navigation menu component

<a [routerLink]="['']" [queryParams]="{ scrollTo: '#home' }">
<a [routerLink]="['']" [queryParams]="{ scrollTo: '#contact' }">
<a [routerLink]="['']" [queryParams]="{ scrollTo: '#about' }">

HTML for the component utilizing the root segment

<componentOne (dataLoadedEvent)="homeLoaded = true; checkIfDataLoaded()"></componentOne>

TypeScript for the component utilizing the root segment

homeLoaded: boolean = false;
contactLoaded: boolean = false;
aboutLoaded: boolean = false;

allDataLoaded: boolean = false;

 ngOnInit() {
    // other code here
    this.route.queryParams.forEach((params: Params) => {
        if (params['scrollTo']) {
            this.checkIfDataLoaded().then(() => { 
                this.scrollToSection(params['scrollTo']);
            });
        }
    });
 }

checkIfDataLoaded() {
    if (this.homeLoaded && this.contactLoaded && this.aboutLoaded) {
        return new Promise((resolve, reject) => {
            resolve(true);
        });
    }
}

As Günter Zöchbauer mentioned in response to another question (), attempting to use promises in this manner may result in a

TypeError: Cannot read property 'then' of undefined
.

TL;DR What is the appropriate method for utilizing promises while waiting for a boolean value to transition to true/false?

Answer №1

The issue lies within your code, specifically in the checkIfDataLoaded() method, rather than due to your usage of booleans.

An error is triggered when the inner condition evaluates to false because at that point, the method returns undefined, leading to an error when calling undefined.then(....

It's crucial for the checkIfDataLoaded() method to always return a Promise if you intend to chain .then() to its outcome.

You might consider implementing something similar to the following:

checkIfDataLoaded() {
    return new Promise((resolve, reject) => {
        if (this.homeLoaded && this.contactLoaded && this.aboutLoaded) {
            // Insert necessary logic here
            resolve(true);
        } else {
            resolve(false);
        }
    });
}

This adjustment ensures that checkIfDataLoaded() consistently delivers a Promise, while allowing flexibility within its functionality.

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

Is using global variables as a namespace a good practice? Creating ambient TypeScript definitions in StarUML

I'm currently working on creating TypeScript type definitions for the StarUML tool. While I've been successful in defining most of the API, I've hit a roadblock when it comes to linking a JavaScript global variable ("type" in this case) with ...

Navigating between two different HTML pages using Angular 2 routing

In my Angular2 application, I have both a front-end section and an admin interface. The front-end section is styled with its own unique set of styles defined in the index.html file. On the other hand, the admin interface has a completely different set of ...

Troubleshooting Cross-Origin Resource Sharing (CORS) in a Spring Boot application:

We are currently working on a project that involves developing a spring boot and angularjs application. The authentication process includes the use of JWT token in combination with LDAP authentication. Once the LDAP authentication is successful, the servic ...

Creating a rotating circle in CSS with ion-slides: A step-by-step guide

Hello, I am attempting to develop a circular object that will rotate in the direction it is dragged. Within this circle, there are elements positioned along the border so that these elements also spin accordingly. To illustrate, below are the specific elem ...

guide for dynamically loading angular modules

In my application, I have three modules: home, moduleA, and moduleB. Within my app component, I am making a call to an API called session which returns a value named mode. Depending on the mode being moduleA or moduleB, I need to lazy load the respective m ...

Obtain user information post-payment with Angular's latest Paypal Checkout 2.0 feature

My app is all set up to sell various items, with PayPal handling the payment process. In order to generate invoices, I need to access user details such as their name and address, which are stored by PayPal for each user. How can I retrieve this information ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Combining Angular 2 RC with Play Framework 2 for seamless integration

I am seeking to combine angular2 rc and play framework 2. Take a look at this example using the beta version https://github.com/joost-de-vries/play-angular2-typescript. One challenge is that rc has different naming conventions and each angular module is ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Attempting to utilize Array Methods with an Array Union Type

Currently, I am in the process of refactoring an Angular application to enable strict typing. One issue I have encountered is using array methods with an array union type in our LookupService. When attempting to call const lookup = lookupConfig.find(l =&g ...

Exploring Angular 17 with the Nebular framework through the implementation of Standalone Components

Exploring Angular in combination with Nebular for UI has been my recent focus. To get started, I decided to create a quick app and dive into the intricacies of these frameworks. After setting up Angular, I initialized a new app using app new my-app. I en ...

Determine user connectivity in Angular 4 using Firebase

My current setup involves using Firebase for authentication with Google. However, I am encountering an issue where upon refreshing the page after being connected, I am unable to retrieve the Session/CurrentUser information. firebase.auth().onAuthStateChan ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

RXJS - Emit values that are strictly greater than the previous value

I am looking to incorporate a scroll listener with rxjs on my website. Currently, the listener emits every scrollY number. Is there a way to create a scroll listener that only emits the scroll position if the number is higher than before WITHOUT NEEDING TO ...

Certain information is failing to be added to the list

userSPMSnapshot.forEach((doc) => { console.log(doc.id, "=>", doc.data()); userSPMList.push(userSPM.fromFirestore(doc)); }); console.log(userSPMList) I'm encountering an issue where some fields in my data lose their values when I p ...

Errors related to TypeScript syntax have been detected within the node_modules/discord.js/typings/index.d.ts file for Discord.JS

I keep encountering typescript syntax errors after pulling from my git repository, updating all npm modules on the server, and running the start script. The errors persist even when using npm run dev or npx tsc. I've attempted the following troublesh ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

Is there a way to transform an angular project into a war file format?

I am trying to build my angular project using visual code and then create a war file. I want to upload this file to tomcat 9 for deployment. Can you please explain how to do this in a simple way? Appreciate your help! ...

What could be causing my sinon test to time out instead of throwing an error?

Here is the code snippet being tested: function timeout(): Promise<NodeJS.Timeout> { return new Promise(resolve => setTimeout(resolve, 0)); } async function router(publish: Publish): Promise<void> => { await timeout(); publish(&ap ...

Firebase console does not show any console.log output for TypeScript cloud functions

I encountered an issue while using Typescript to write some Firebase cloud functions. Here is a snippet of my code: index.ts export * from "./Module1"; Module1.ts import * as functions from "firebase-functions"; export const test = functions.https.onR ...