Unable to modify external variable within the subscribe function in Angular using Typescript

I have a code snippet below where I am trying to query the backend to check if an email is already registered or not. However, no matter what email address I pass to the verifyEmail function, the "registered" variable always remains false. How can I update the "registered" variable based on the response from the backend? Thank you.

export class MyClass {

   registered: boolean = false;
   message: string = ''

   verifyEmail(email) { 
        this.registered= false
        
        let verifyEmailUrl = "/backend/GetUserByEmail";
        this.http.post(verifyEmailUrl, {
            email: email
        }).subscribe(
            (data) => {
                if (data["user"]) { // can find a user
                    this.message = 'This email has already been registered'
                    this.registered= true
                }
            });
}

Answer №1

Your implementation with an arrow function indicates that the scope should be shared, and the variable this.registered needs to be updated accordingly. To better diagnose the issue, consider including a console.log output of relevant data or additional code snippets. It seems that the root cause is not clearly evident based on the provided information.

Answer №2

Are you wondering how to check the registered value? It's not possible to retrieve this value immediately after executing verifyEmail because it will be updated at a later time. One way to handle this is by creating a BehaviorSubject, subscribing to it, and accessing the registered value once it updates.

export class MyClass {

   registered$ = new BehaviorSubject<boolean>();
   message: string = ''

   verifyEmail(email) {             
        let verifyEmailUrl = "/backend/GetUserByEmail";
        this.http.post(verifyEmailUrl, {
            email: email
        }).subscribe(
            (data) => {
                if (data["user"]) { // can find a user
                    this.message = 'This email has already been registered'
                    this.registered$.next(true)
                } else {
                    this.registered$.next(false)
                }

            });
}

In your main code:

myClassObject.registered$.asObservable().subscribe(registered => console.log(registered));

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

Dynamic Color Changes on Highcharts Sunburst Based on Hierarchy Levels

Is there a way to dynamically adjust the color of layers in a sunburst chart when changing levels? Take a look at our example chart: https://i.sstatic.net/6cEdg.png When clicking on a continent like Asia, the chart should display like this: https://i.sst ...

Simpler and more sustainable methods for embedding HTML elements using a configuration file

Currently, I am devoting my time to a toy project that heavily relies on JavaScript. A key component of this project is a JSON file that contains configurations and input descriptions, along with range values and options. This JSON file enables me to easil ...

The Malihu jQuery Custom Scrollbar integrated with Meteor is failing to display on the webpage

I have successfully integrated Malihu's custom scrollbar into my meteor app using this package: The code I'm using is as follows: Template.post.rendered = function() { $('body').mCustomScrollbar({ theme: 'minimal-dar ...

An error is displayed when attempting to construct an express-react application

Currently, I am working on a project in React and ExpressJS that was previously worked on by someone else. When attempting to run the command npm run build An error is displayed in the project: https://i.stack.imgur.com/PsfpS.png How can I resolve thi ...

Selecting the appropriate technology or library for incorporating user-defined text along a designated path within established areas

I am currently developing an admin dashboard with CodeIgniter 2 that allows the admin to upload custom images, particularly ones with blank spaces for text overlay. The goal is to enable regular users to add their desired text in specific areas defined by ...

Displaying an image with Jquery on hover

Edit2: Hello Everyone, I'm looking to implement a hover effect over the "durchwahl" text that displays a profile image when hovered. However, I am facing an issue where the image moves out of the visible area at the bottom of my page. Is there a way ...

What are the best practices for utilizing *ngIf?

In my Angular project, I am facing a challenge with using *ngIf. My app.component.html file handles both the login page and the dashboard. I want to hide the dashboard until the user logs in. To achieve this, I decided to use *ngIf. Here is how I implement ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

Explore the routing capabilities of the HERE Maps JS API, including features for ABR and height

Recently, I've encountered an issue with the HERE maps JS API routing feature. Specifically, I'm attempting to add restrictions based on factors like height or weight. Despite my efforts, it seems to be disregarding these restrictions. Additional ...

Having Issues with Loading More Button Functionality in Selenium Automation

Here is a snippet of my code. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected ...

Guide to utilizing the PWA file manager in conjunction with Vue 3

I am trying to create a custom file extension (.vc2d) that will open in my Vue and Typescript progressive web app. I have set up file_handlers in my web manifest file and used window.launchQueue in my PWA. However, when I double click on the file in File E ...

What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidd ...

Challenges associated with the '--isolatedModules' flag and RouterContext

After attempting to run my deno application, I encountered the following error message and I'm unsure about the cause. Has anyone else faced this issue before? Command used to run: deno run --allow-all server.ts Error: Error: TS1205 [ERROR]: Re-expo ...

The class type "selectLabel" passed to the classes property in index.js:1 for Material-UI is not recognized in the ForwardRef(TablePagination) component

Just started using react and encountering a repetitive error in the console after adding this new component. Here is the full error message: Material-UI: The key selectLabel provided to the classes prop is not implemented in ForwardRef(TablePagination). ...

Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it. Here is an array of objects: [ { "date": "2015-01-01T12:00:00.000Z", "photoUrl": "", ...

C# Audio Visualizer: Enhancing Your Sounds With Visual

I am currently developing an audio visualizer using C#/Asp.net/JavaScript for a website. To ensure that my animations move smoothly in sync with the music, I have decided to preprocess the MP3 file within the code backend. I plan to write the values and fr ...

Contrast between utilizing a WebApp that connects to an API and one that relies on backend

Whenever I develop simple web applications, I often begin by setting up a nodeJS backend, usually creating an API server with ExpressJS. When specific routes are accessed, the server responds by dynamically rendering HTML from EJS based on the current conn ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

Tips for retrieving the option text value following an onchange event in AngularJS

Whenever I change the selection in my dropdown menu for 'Cities', the alert is displaying the value of the previous selection instead of the current one. For example, if I select a state and then switch to Cities, the alert shows the text related ...

I am sending JSON as form data using JavaScript and then accessing it in PHP. During this process, the quotation marks are being replaced with their HTML entity equivalent

After converting an array into JSON, I send it as a value of a text box using the post method. In a PHP file, when trying to print it out, it displays some encoding issues. var json_arr = JSON.stringify(info); The generated JSON looks like this: {"1":"1 ...