Retrieving the Angular API response from a service and passing it to a component

One challenge I encountered in my Angular 12 application is capturing the response of an API call made in the service file within my component. The issue arises from the asynchronous nature of the API response, which causes the console to always display 'undefined'. Despite attempting to use async await, I have yet to find a solution:

WITHIN THE SERVICE FILE:

public checkEmail(emailToVerify: any) {
    this.myService.emailValidate({ email: emailToVerify }).subscribe({
      next: (data: { result: any) => {
        console.log('updateEmail-res', data);
        return data;
      },
      error: (err: any) => {
        console.log('updateEmail-err', err);
      }
    });
  }

WITHIN THE COMPONENT:

this.apiResponse = await this.myService.checkEmail(customerEmail);
 console.log("this.apiResponse", this.apiResponse)

Answer №1

Within Component

verifyEmailAddress = async () => {
    const parameters = {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="730716000733141e121a1f5d101c">[email protected]</a>',
    };
    const responseFromAPI: boolean = await this.emailService.verifyEmail(parameters);
    console.log(`Response from API is ===`, responseFromAPI);
  };

Inside Service

export class EmailService {
  constructor() {}

  verifyEmail = async (params: {
    emailAddress: string;
  }): Promise<boolean> => {
    return new Promise((resolve) => {
      const isValid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(
        params.emailAddress
      );

      resolve(isValid);
    });
  };
}

Answer №2

The checkemail method serves no purpose. If you already have emailValidate, there's no need for another redundant method. Just use emailValidate directly.

this.apiResponse = await this.myService.emailValidate({ email: customerEmail});
 console.log("this.apiResponse", this.apiResponse)

Furthermore, in your component:

this.myService.emailValidate({ email: customerEmail}).subscribe({
          next: (data: { result: any) => {
            console.log('updateEmail-res', data);
             this.apiResponse = data;
          },
          error: (err: any) => {
            console.log('updateEmail-err', err);
          }
        });

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

What sets apart TypeScript's indexed types from function signatures?

I am curious about the distinction between indexed type and function signatures in TypeScript. type A = { _(num: number): void; }['_']; type B = { _(ten: 10): void; }['_']; let a: A = (num) => { console.log(num); }; let b: B ...

"I encountered an error stating that res.json is not a function while trying to establish a connection between ReactJS

dataset.list.js import React, { Component } from "react"; import Datasets from "./data"; import axios from "axios"; class App extends Component { render() { return <Datasets datasets={this.state.datasets} />; } ...

What is the best way to vertically center an item at the end of a card in Bootstrap 4?

In the process of creating a long bootstrap card containing two rows of information including a title and description, I encountered an alignment issue with the button. The button is intended to be aligned to the right of the card while remaining centered. ...

Obtain the hexadecimal color code corresponding to the level of humidity

I am in search of a formal method to determine the hexadecimal color based on a percentage value of relative humidity. Here is an illustration of the color range I aim to utilize, it being the most widely used. Is there a specific technique that I can em ...

Is there a way to utilize nodemon without having to install it through npm?

I'm having trouble with my network not allowing me to use npm install. Is there another way for me to install and use nodemon? I've noticed that Node only runs after setting PATH variables on Windows. I attempted to set the path for nodemon, but ...

How can you selectively send only the values of chosen checkboxes when dealing with hidden inputs that share the same name?

Is there a way to send only the values of selected checkboxes that are linked to hidden fields with the same name in PHP? php <input type"checkbox" name="<?echo $filename;?>_<?echo $variable;?>" id="filename_<?echo $variable;?>" valu ...

Keep track of the input values by storing them in an array after they are

Creating an Angular application to read barcodes. barcode-scanner.component.html <form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)"> <div class="text-center"> <input type="text" maxlength= ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

The 'push' property is not found within the 'Control' type

I am attempting to create an array that contains arrays within it. This array is intended for a dynamic form functionality, where the user can add a new section and push the array of control fields to the main array. Angular2 then generates this dynamical ...

Attempting to push my code changes to update my Angular website, however, encountering an error message in the console

Seeking help to resolve an error in my Angular app development using Visual Studio Code. Every time I try to publish updates, I encounter the following issue: __vite-browser-external:console:3 Uncaught Error: Module "console" has been externaliz ...

Having an issue in Reactive Form where the nested formControlName is not capturing the value

How can I store a value in a nested reactive form when the nested formgroup is not accepting the value? this.signupForm=new FormGroup({ username:new FormControl(), email:new FormControl(), jobDetail: new FormGroup({ code:new FormControl(), p ...

Move the object in Three.js by rotating it around the origin (0,0,0) in response to mouse

I am currently working with an object in Three.js that was created in Blender and imported into the Three.js format. My goal is to enable mouse rotation for this object. Any assistance on how to achieve this would be greatly appreciated! Thank you. ...

What are the steps for transforming this code into pure CSS, or incorporating it into a Javascript function?

@function generate-random-box-shadows ($n) $value: '#{random(2000)}px #{random(2000)}px #FFF' @for $i from 2 through $n $value: '#{$value} , #{random(2000)}px #{random(2000)}px #FFF' @return unquote($value) $random-shadows1 ...

I attempted to copy the "koa" module from my node_modules folder to a custom typeRoots directory, but it doesn

I want to use Ant Design UI, and I hope to import the script tag with the .min.js label, like this: <script src="//cdn.staticfile.org/react/15.4.1/react.min.js"></script> <script src="//cdn.staticfile.org/react/15.4.1/react-with-addons.min. ...

Unexpected behavior with Ember.js Ajax request

I recently started using the Ember.js framework. While attempting to make an AJAX call from the framework, I encountered unexpected results. Below is the code snippet on the page - Link to the first AJAX call, which is functioning as intended. {{#linkT ...

What is the process for transferring the value from a list item to the search field box?

I have developed a Bootstrap/jQuery function that can display the item matching the user's search query. However, I am facing some challenges in making the selected item populate the search field or providing clear validation to the user once it is ch ...

Creating a React lightbox feature where users can click on the first image and view it, but the subsequent images are displayed as empty

While creating this lightbox in React, I encountered an issue where the next image in the array appears empty and shows "Object object" as the error. I am extracting both the image and text from the array of objects. Does anyone have any suggestions? The ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Develop a component library for Angular 2 without incorporating inline styles

I recently came across an interesting article about developing an Angular 2 component library that utilizes inline styles. Is there a method to create a library in Angular 2 without relying on inline styles? I also stumbled upon another resource, but it d ...

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...