Executing an if statement in Ionic Angular on a separate page

One challenge I'm facing is redirecting users to a profile setup page when they first log in. To achieve this, I have implemented an if statement in my code that checks if the user's id exists in a firebase database and is associated with a profile. If not, the user is directed to a profile creation page. Once they create a profile, they are then taken to their profile. However, there seems to be an issue where the profile page continues to load even after the login process has been completed and closed. Why is this happening?

login.ts

login(user: User){
 this.afAuth.auth.signInWithEmailAndPassword(user.email,user.password)
 .then(res => {
   //check if user has made profile if not send to profile setup page
    let user = firebase.auth().currentUser;
    if(user.emailVerified){
      this.afAuth.authState.take(1).subscribe(data => {
        let profileCollection = this.afs.collection('profiles').doc(`${data.uid}`).valueChanges();
        profileCollection.subscribe(userProfile => {
          if (userProfile == null){
            console.log(userProfile);
            this.navCtrl.setRoot('ProfileSetupPage');
          }else{
            console.log('LoginPage Load Tabs Page');
            this.navCtrl.setRoot('ProfilePage');
          }
        })
      });
    }
 }

profile-setup.ts

 createProfile(){
   if(this.profileForm.valid){
     this.afAuth.authState.take(1).subscribe(auth => {
       this.afs.collection('profiles').doc(`${auth.uid}`).set(this.profile)
         .then(res => {
           this.navCtrl.setRoot('ProfilePage');
         })
     })
   }

Answer №1

It's important to remember to unsubscribe from the login events before redirecting or initializing in the profile-setup.ts file, as the subscribe for the login is still active and accepting events.

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

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

The interconnectivity between ngAfterViewInit in Angular's LifeCycle and observables

enable.service.ts @Injectable({ providedIn: 'root' }) export class EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: fals ...

Transitioning to Vue 3 has introduced a change where prop types are now classified

During the process of migrating the application from Vue 2 to Vue 3 by following this guide: , I encountered an issue related to Props and their types. All props were marked as type unknown by the linter, even though no errors were shown in the template it ...

Modify a field's value based on a change in another field's value

Imagine a scenario where you have two fields defined within a class: export class SomeClass { selectedObjects: MyClass[]; fieldToUpdateWhenArrayAboveChange:string; } Given the example above, the goal is to automatically update the second field ...

How to create a separate modal component in Angular without relying on ng-modal

I am facing an issue with ComponentB, which contains HTML code for a Bootstrap modal. I want to open ComponentB from ComponentA. Although the component is getting loaded when inspected, the popup modal does not appear on the UI. <app-root> <ap ...

How can you exclude templates in an Angular 7 CLI build to incorporate MVC views?

Currently, I am exploring the latest updates in Angular (7+) and CLI. After completing parts of the 'Tour of Heroes' tutorial, I have been able to use 'ng build' to generate production files. However, a key requirement for me is using ...

Creating an Injectable AppSettings Class in Angular 2

Currently, I am working with Angular 2 within an ASP.NET Core application, although the specifics of that setup are not crucial to my current issue. My main task at hand involves fetching configuration values from the server and integrating them into my An ...

Issue: The parameter "data" is not recognized as a valid Document. The input does not match the requirements of a typical JavaScript object

I encountered the following issue: Error: Argument "data" is not a valid Document. Input is not a plain JavaScript object. while attempting to update a document using firebase admin SDK. Below is the TypeScript snippet: var myDoc = new MyDoc(); myDo ...

Testing the Confirmation Popup in Ionic Framework Using Karma for Unit Testing

I am struggling to test both outcomes of a confirmation box using karma and jasmine. Despite receiving some assistance, I am finding it challenging to mock the ionicPopup. I would like to be able to test everything from the ng-click that triggers the box ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Unable to find the correct path in my NodeJS/Express/Typescript application

Having trouble with my '/api/users' route that doesn't seem to be properly defined in my routes setup. When attempting to access /api/users from the browser, it just sticks in a repeated loop. app.ts import * as express from "express" impo ...

I continue to encounter the same issue: running the command node-pre-gyp install --fallback-to-build --library=static_library

As I try to deploy my application to Heroku, I keep encountering the error message 'node-pre-gyp install --fallback-to-build --library=static_library'. Despite trying various suggestions such as downgrading the Firebase or node-pre-gyp versions, ...

Instantiate the component array upon object instantiation

I'm currently in the process of learning Angular 2, so please bear with me if this question seems trivial. I am attempting to create a dynamic form that can be bound to a model. However, I am encountering an issue where I am unable to initialize my ar ...

Ensuring File Size and Format Compliance in Angular's HTML and TypeScript

I'm currently tackling a file upload feature on an ASP.net webpage using Angular. I have a question: How can I verify if the uploaded file is either a PDF or JPG and does not exceed 2MB in size? If these conditions are not met, I would like to displa ...

The functionality to subscribe in ts(6385) has been marked as

I am encountering an error message regarding the deprecation of the subscribe function in my code. The issue seems to be with the second part of the code for the getStarwarsHeroes function, where the .subscribe method is being deprecated. import { Injectab ...

Having difficulty importing JSON data containing arrays into the Firebase Realtime Database

Typically, I create a duplicate of a Node by using the 'Export JSON' option in the 3 dots menu located at the top right corner. https://i.sstatic.net/9sUat.png Afterwards, I navigate to another path and import the same JSON file. A few days ago ...

Sorting elements with a custom selector using Angular's ViewChild

Currently, I am delving into the realm of angular ViewChild. However, I find myself facing a roadblock when attempting to utilize ViewChild in selecting custom reference variables from the DOM. Within my template lie two tables: <mat-table #eventTable ...

Contrasting between betting text and console error logging in Angular

Currently working on an Angular application and exploring the best practices for error logging. I'm pondering whether to opt for console logging or text-based logging. Text-based logging seems beneficial as it stores historical error data on the serv ...

Angular version 16+ is incompatible with Three.js and does not function properly together

I am attempting to integrate three.js into my Angular 16 project and encountering the following error message: npm i @angular-three/core npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email&# ...