Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing the close action, then I need to log in with that data and return an observable result.

loginModal() : boolean {

    this.dpDialogService.input(
        'Login',
        [
            {
                label: 'Username/Email', 
                form: 'username', 
                data: '', 
                validators: [Validators.required],
                validatorMsg: 'Username is required.'
            },
            {
                label: 'Password', 
                form: 'password', 
                data: '', 
                validators: [Validators.required],
                validatorMsg: 'Password is required.',
                type: 'password'
            },
        ]
    ).then(
        close => {
            this.login({username: close.username.value, password: close.password.value}).subscribe(
                loginResult => {
                    return true;
                },
                errorResult => {
                    this.dpDialogService.error('Invalid username/password.');
                    return false;
                }
            )
        },
        dismiss => {
            return false;
        }
    );
}

I am looking for a way to return a boolean value from this function. It seems like using a promise might be necessary, but I'm unsure how to handle it given the nested structure.

Answer №1

In the event that .subscribe does not provide a promise, it is necessary to manually create a promise that will resolve to either true or false based on the outcome of .subscribe.

It seems that the resultant promise must always resolve and never reject (as indicated by the dismiss => code).

).then(
    close => {
        return new Promise((resolve, reject) => {
            this.login({username: close.username.value, password: close.password.value}).subscribe(
                loginResult => {
                    resolve(true);
                },
                errorResult => {
                    this.dpDialogService.error('Invalid username/password.');
                    resolve(false);
                }
            )
        })
    },
    dismiss => {
        return false;
    }
);

Answer №2

Here's the solution, big thanks to Jaromanda X for the assistance!

displayLoginModal() : Promise<boolean> {

    return new Promise((resolve, reject) => {
        this.dpDialogService.openDialog(
            'Login',
            [
                {
                    label: 'Username/Email', 
                    form: 'username', 
                    data: '', 
                    validators: [Validators.required],
                    validatorMsg: 'Please enter your username.'
                },
                {
                    label: 'Password', 
                    form: 'password', 
                    data: '', 
                    validators: [Validators.required],
                    validatorMsg: 'Please enter your password.',
                    type: 'password'
                },
            ]
        ).then(
            success => {
                this.login({username: success.username.value, password: success.password.value}).subscribe(
                    result => {
                        resolve(true);
                    },
                    error => {
                        this.dpDialogService.error('Invalid username/password combination.');
                        resolve(false);
                    }
                )
            },
            failure => {
                resolve(false);
            }
        );
    });

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

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...

Exploring [routerLink] vs routerLink: Unraveling the Distinctions

Can you explain the distinction between [routerLink] and routerLink in Angular routing? What are the advantages of each one and which should be used? Understand the difference ...

Use JQuery to load a particular page by specifying its ID with the hashtag symbol

I am facing an issue where I need to create multiple private chatrooms per user. Although I have managed to make it work, I encountered a problem where if there are more than one private chats happening simultaneously, the content of these chats gets broad ...

Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this: interface Product { id: number; name: string; ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

How can we transfer functions between files in JavaScript when creating a service library?

There's a piece of code located in my identity service that I'm working with. export function sumbitLogin(username, password) { console.log(username, password); } I want to simplify the process of accessing services in my components without ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

What is the best way to retrieve multiple model values from a single selection in AngularJS?

I recently started learning AngularJS and have a basic question to ask. I have a select box that allows users to choose a country from a list of countries. Currently, when a country is selected, only the country code is stored in the model. However, I woul ...

Using Three.js to create a React button positioned above a canvas

Here's the code I have written using three.js in a React component. I am looking to add a button above the canvas. How can I achieve this? Additionally, I would like to know how to add a click event on objects rendered in three.js. import React, { Com ...

JavaScript alerts

Can anyone recommend a quality library with beautifully animated popups? Specifically, I need a popup that allows for basic HTML fields such as text areas and more.... I am in search of a popup that will overlay on the current page, rather than opening a ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...

The function inArray() in jQuery will return a value of -1 when an array consists of

When using jQuery inArray, if the array contains only one element, it will return -1. var a = Array(1); console.log($.inArray(1,a)); This result is -1. However, if the array has 2 or more elements, it functions correctly. var a = Array(1,2,3); console.l ...

Is there a method to hide an HTML form completely?

Is there a way to quickly hide an HTML form from a webpage once the submit button is clicked and replace it with the result of a .php file in the most efficient manner possible, with minimal code? ...

What is the best way to combine several packed props simultaneously?

After attempting the following, I encountered the following error: Unhandled Runtime Error TypeError: navbar.makeButtonClick is not a function Source .next/static/chunks/pages/index.js (19:29) @ onClick 17 | return( 18 | <button href='#&apo ...

Guide to downloading a CSV file directly from a webpage built with vue.js

Delving into the world of vue.js, I find myself pondering over how to incorporate a download link in my webpage for a CSV file stored locally. In my component Template.vue, I have the following structure: <a :href="item.loc" download> {{item.title ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

Display information in a different sequence on the webpage compared to how it is stored in the

I'm struggling to display data from a database in a different order on my webpage. The table in my database has three columns: Day of the week, Open from, and Open to, which represents the opening hours for specific days of the week. Here is how it lo ...

In React, what is the correct term for "selection boxes" when choosing multiple items in Finder?

I'm in search of a React component that allows me to select multiple elements on the screen by clicking, holding, and forming a square around them. I've tried searching for terms like 'selection box' and 'React select elements,&apo ...

Getting the Firebase Project Name or ID from a Cloud Function is a simple task that involves using

While working with Cloud Functions, I need to retrieve the project name from one of my Javascript server files. The project name is stored in .firebaserc file, but I am not sure if this file is accessible on the server side. Is there a way to achieve somet ...