In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a collection exists. The issue I am encountering is that even when the value does exist, it enters the conditional "if" statement block as intended; however, it also proceeds into the "else" statement. I attempted incorporating a break statement within the "if" block but unfortunately it did not yield the desired outcome.

Here is a snippet of the code:

register() {
this.api.getLoginInfo().pipe(take(1)).subscribe(res => {
  for (let i = 0; i < Object.keys(res).length; i++) {
    this.checkem = res[i].payload.doc.data()['email'];
    if (this.registerForm.value.email !== this.checkem) {
      alert("Registered Successfully");
      this.router.navigate(['/first']);
      localStorage.setItem("isLogged", "true");
    } else {
      console.log("Already Registered");
      alert("Already Registered!");
    }
  }
});

}

Furthermore, here is the related API Service method:

getLoginInfo() {
return this.firestore.collection("users").snapshotChanges();}

Answer №1

Currently, I have resolved the issue by utilizing a firestore "where" query.

In my Angular service, the code looks like this:

getlogindetails(email) {
    return this.afs.collection('users', ref => ref
      .where('email', '==', email)
    ).get();
}

And in my component:

register() {
    this.submitted = true;
    this.api.getlogindetails(this.registerForm.value.email)
      .pipe(take(1)).subscribe(res => {
        if (!res.empty) {
          alert("Already Registered!");
        } else {
          this.router.navigate(['/first']);
          localStorage.setItem("isLogged", "true");
      });
  }

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

There was an issue with a promise rejection related to FirebaseError, specifically when the function addDoc() was called with invalid data containing an unsupported field value represented by

I am encountering an issue while trying to post data in the firebase firestore database. I can successfully post prewritten titles into the database, but I face challenges when trying to add custom titles from an input field. Here is the traceback error m ...

How can I trim a value using one-way data binding in Angular?

Is there a way to trim values in Angular using one-way data binding? Can this be done directly in the component.html file rather than in typescript? I tried the following but it didn't work: <P>{{country.trim()}}</P> Thanks ...

Customize Angular Material styles uniquely across various components

Within my application, I am utilizing two components that contain tab groups. The first component serves as the main page, where I have adjusted the CSS to enlarge the labels by using ViewEncapsulation.None. The second component is a dialog, and I aim to m ...

Is there a way to instruct Alexa/Jovo to incorporate just one render document in its response?

Within my project, there are multiple outputs, but I am specifically focused on an output that presents 2 directives: an APL and an APLA render document. My component is set up to handle this in the following way: @Handle({ global: true, prioritiz ...

What potential outcomes arise from independently initiating multiple components simultaneously?

Here is a scenario where I am able to achieve the following: @NgModule({ imports: [BrowserModule], declarations: [AppComponent, BComponent], bootstrap: [AppComponent, BComponent] <---------- here two components }) By doing this, it will ge ...

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

`How can I enhance the appearance of an Angular 4 component using an attribute?`

There is a component where I need to pass specific data to the child components within an ngFor loop using attributes. Depending on the attribute, I want to style these child components accordingly. Code testimonials.component.html - (Parent component) ...

Difficulty with setting up Typescript in Visual Studio Code on MacOS Catalina

I'm currently facing an issue that appears to be related to the environment. How can I resolve it? And how do I link the installed TSC to my console? Steps to Recreate: npm install -g typescript was able to successfully install or update [email ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

What is the best way to stop webpack from generating typescript errors for modules that are not being used?

The directory structure is set up as follows: └── src ├── tsconfig.json ├── core │ ├── [...].ts └── ui ├── [...].tsx └── tsconfig.json Within the frontend, I am importing a limi ...

Is there a feature in Angular 2+ (specifically Angular 7) that allows for comparing code differences

Is there a code comparison component or plugin available for Angular 2+ (specifically Angular 7) that can compare two separate text files? In our current AngularJS application that we are upgrading, we currently use Ace-Diff and it works effectively. Howe ...

Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume ...

Referencing another document in Cloud Firestore: a comprehensive guide

Currently utilizing Angularfire2. Let's say there are users and comments collections. When a comment is added, what is the proper way to reference the user who made the comment? Initially, I considered creating a comment with a structure like this: ...

Creating conditional observable debounceTime

I've implemented a basic debounce on an input element event in the following way: Observable .fromEvent(this.elInput.nativeElement, 'input') .debounceTime(2000) .subscribe(event => this.onInput(event)); Is there ...

Plugin for managing network connectivity in Ionic framework

In order to check if internet and id connection are available, I need to make a server request. I have implemented the Ionic Native Network Plugin following their official documentation. Here is my code snippet: import { Component } from '@angular/c ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

When using Typescript, the keyof operator for objects may not undergo refinement and can result in error

I've been working on creating a function that validates whether a key in an object is a non-empty string. export const validateRequiredString = <T>( obj: T, key: keyof T & (string | number) ): void => { if (typeof obj[key] !== " ...

Tips for safely sanitizing an HTML file containing both HTML tags and JavaScript functions within an Angular application

I am trying to bind an HTML file that contains both HTML and JavaScript (jQuery) functions into my Angular application. Here is how I bind my HTML file into the component's HTML: <div [innerHTML]="currentDetailEntry?.content | sanitizeHtml">&l ...