Prep yourself for an incoming response from an object in Angular 9

Greetings, this is my debut post here so my apologies if I am not following the correct procedures.

As a novice in Angular with no experience in synchronism, I kindly request that any explanation be kept as simple as possible.

I am currently working with a function in my service:

 validateDDBB(userName, teamName, email: string) {
    let requestUrl: string = '/api/tenniship/validator/user?userName=' + userName + '&teamName=' + teamName + '&email=' + email;
    const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
    return this.http.get<Array<boolean>>(requestUrl, config);
  }

This function is intended for a Sign Up form. It serves to check if an email, username, and teamName are already registered in the database. The function returns a boolean array with a size of 3, indicating their existence or absence.

The issue I am facing is that the code is not waiting for the response, resulting in the use of incorrect data.

Here is my component function:

databaseValidator(){
    this.loginService.validateDDBB(this.username, this.teamName, this.email).subscribe(
      res => {
        this.usedUsername = res[0].valueOf();
        this.usedTeamName = res[1].valueOf();
        this.usedEmail = res[2].valueOf();
        console.log("Data base info pulled: " + res);
        return true;
      },
    error => {
      console.error("Something went wrong: undefined: " + error);
      return false;
    }
    );
  }

How can I adjust my code so that when I call this function, it waits for the response and avoids using incorrect data?

onSubmit(){
    this.databaseValidator();
    //usedUsername, usedTeamName, and usedMail are boolean variables.
    console.log("Username: " + this.usedUsername);
    console.log("Team: " + this.usedTeamName);
    console.log("email: " + this.usedEmail);
}

Thank you very much!

Answer №1

databaseValidation function will execute first, followed by console messages, and then the login process will be completed. There are various options to address this issue, such as using a callback, returning an observable, or a promise.

One way to handle it is by returning a promise.

databaseValidation() : Promise<any> {
   return new Promise((resolve, reject) => {
    this.loginService.validateDB(this.username, this.teamName, this.email).subscribe(
      res => {
        this.usedUsername = res[0].valueOf();
        this.usedTeamName = res[1].valueOf();
        this.usedEmail = res[2].valueOf();
        console.log("Database information retrieved: " + res);
        resolve()
      },
    error => {
      console.error("An error occurred: undefined: " + error);
      reject()
    }
    );
  }

onSubmit(){
    this.databaseValidation().then(()=>{

    console.log("Username: " + this.usedUsername);
    console.log("Team: " + this.usedTeamName);
    console.log("Email: " + this.usedEmail);
    })  
}

Since databaseValidation returns a promise, we can use async/await.

async onSubmit(){
    await this.databaseValidation();

    console.log("Username: " + this.usedUsername);
    console.log("Team: " + this.usedTeamName);
    console.log("Email: " + this.usedEmail); 
}

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

Error429 was received from a GET request made to the Imgur API

Encountering a Request failed with status code 429 error from the Imgur API despite using a new Client_ID that hasn't been used before, Here is my Api.ts: const imgurClientId = process.env.NEXT_PUBLIC_Client_ID const BASE = "https://api.imgur. ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

The term "Exports" has not been defined

I'm currently facing a challenge trying to develop an Angular application based on my initial app. The process is not as smooth as I had hoped. Here's the current setup: index.html <!DOCTYPE html> <html> <head> <base h ...

I am having trouble retrieving child interface data from API using Angular. Can someone help me figure out what I am doing

Recently started with Angular 7 and could use some guidance. I have a JSON stream that appears as follows: { "Id": 25, "Name": "XYZ Corp", "CompanyAddresses": [ { "Id": 39, "CompanyId": 25, "Address1 ...

Struggling to accurately capture the values from checkboxes and dropdown selections to ensure the correct data is displayed. Assistance is needed in this

I am facing challenges in retrieving the accurate data for display from Mat-Select and Mat-Checkbox components. My goal is to capture the selected values from users and perform if-else statements to validate conditions, displaying the correct data view if ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Issue with angular 8 radio button not being selected

Here is the HTML code I am working with: <div *ngFor="let option of systemEquipmentGroup"> <h5>{{option.optionGroupName}}</h5> <div> <label style="display: block;" * ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

The defaultRowRenderer is causing issues with my Jest unit test. It seems to be related to an object with an anonymous import of createMulti

Encountering a failure in jest unit-tests when using the defaultRowRenderer method in react-virtualized for a Table component, with the error message: ...node_modules\react-virtualized\dist\es\Table\index.js:1 ({"Object.<anonym ...

Ensure that column headers remain fixed when scrolling side to side

I'm trying to adjust the column headers so that I can scroll horizontally while keeping the headers visible. I've attempted the following changes but haven't been successful. In the screenshots provided, you can see that when I scroll up or ...

Set up the configuration for express to access an external API through proxy.conf.json while in production mode

I am currently managing two applications on Heroku, one being myserverapi (built with Spring Boot) and the other being a client-side Angular app named client. The server is hosted at myserver.heroku.com while the client resides at myclient.heroku.com. At t ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Expanding the capabilities of i18next's translation function

I'm having trouble properly extending the function. I am stuck with the error Cannot redeclare block-scoped variable t. I am unsure if declaring a module is the correct approach (I am new to TypeScript). I have also tried creating a wrapper for the t ...

Discover the step-by-step guide to setting up forwarding in React Router 5

Just diving into the world of React and TypeScript. I'm working with a component called Err. Is there a way to redirect it using React Router 5? import React, { FC, Fragment, useEffect } from "react"; const Err: FC<{ error: string }> = ({ erro ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Monorepo with Yarn workspaces using Typescript and Node.JS project encounters "module not found" error while running nodemon

After creating a monorepo with yarn workspaces for a TypeScript Node.js project, I encountered an issue with local development. Despite successfully building the project, I faced errors when running yarn dev without first manually running yarn build. The e ...

The TypeScript function was anticipating one argument, however it received two instead

Can you help me fix the issue with my createUser() function? Why am I unable to pass parameters in Smoke.ts? Login.ts : interface User { url: string, email: string, } class Test{ async createUser(user: User) { await Page.setUrl(user.url); aw ...

Learn how to connect a value to a dropdown in Angular when updating existing data

I am currently working on a dropdown feature that populates with an array of options. Additionally, I have local data that loads in a dialog box when a user selects a row in a table for editing purposes. My goal is to have the selected value from the drop ...