I am facing an issue with Firebase AngularFireAuth where I am unable to update a user's email even though the

I am facing an issue with my Angular Application where I cannot change the email of a logged-in authenticated user in Firebase.

Fetching the email as an observable works fine:

    getUserEmail():Observable<string | null>{
        return this.afAuth.authState.pipe(map(user => user? user.email : null));
    }

However, when attempting to update the user's email, it only returns an observable:

    updateUserEmail(newEmail: string){
        return this.afAuth.authState.pipe(map(user => user? user.updateEmail(newEmail) : null));
    }

Below are the relevant parts of the service:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';
import { from, Observable, Subject } from 'rxjs'; 
import { map } from "rxjs/operators";
import { UIService } from '../shared/ui.service';

import { AuthData } from "./auth-data.model";
import { UserData } from './user-data.model';
import { User } from "./user.model";
import { UserService } from './user.service';

@Injectable()
export class AuthService {
    public authChange = new Subject<boolean>();
    private isAuthenticated: boolean = false;
    public userLoggedIn: User | null = null;
    public userUID$: Observable<string>;

    public auth: any;

    constructor(private router: Router,
                private afAuth: AngularFireAuth,
                private uiService: UIService,
                private user: UserService) 
                {
                    this.userUID$ = afAuth.authState.pipe(map(user => user? user.uid : null));
                    
                }

    getUserEmail():Observable<string | null>{
        return this.afAuth.authState.pipe(map(user => user? user.email : null));
    }

    updateUserEmail(newEmail: string, password:string, oldEmail:string){
        return this.afAuth.authState.pipe(map(user => user? user.updateEmail(newEmail) : null));
    }

}

Answer №1

After a bit of troubleshooting, I finally cracked the code. The solution was to include the necessary AngularFireAuthModule and reauthenticate the user before updating the email address:

This is how I made changes to my service method:

    updateUserEmail(newEmail: string, password:string, oldEmail:string){
        return from(this.afAuth.signInWithEmailAndPassword(oldEmail, password).then(userCredentials => {
                    return userCredentials.user.updateEmail(newEmail);
        }))
    }

And here's my updated Firebase module setup:

import { NgModule } from '@angular/core';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { environment } from 'src/environments/environment';
import { AngularFireAuthModule } from '@angular/fire/auth';

@NgModule({
  imports: [
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFirestoreModule
    
  ],
  exports: [
    AngularFireModule,
    AngularFireAuthModule,
    AngularFirestoreModule
  ]
})
export class  AppFirebaseModule { }

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

Exporting External JavaScript Variables in Angular 2 Using Typescript

In my Configuration JS file, I have defined some configuration variables. For example: var config = {url:"xyz.com"}; I need to access these configuration parameters throughout my application. I attempted to export the config variables like this: export ...

Strategies for patiently waiting for an object to appear before loading the HTML

After logging into my service, I download data from a REST API, and based on that data, I display certain tabs. However, I am experiencing issues with loading the HTML content once the data has been retrieved. The ngif directive at the beginning of the H ...

What's Preventing TypeScript Enum Keys from Being Transformed during Compilation?

I've encountered an issue while working on a project with TypeScript, Webpack, Babel, and React. The problem arises when trying to use enum members as keys for an object. Here's a snippet of the problematic file: // traits.ts import { Trait } fr ...

The directive is dynamically altering the disable attribute of its parent element

I am faced with a scenario where I have both a button and a directive in my template. The button can be disabled based on certain parameters defined in the template itself, as well as by the directive (it gets disabled in case of a double click event). B ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

Typescript Algorithm - Node Tree: A unique approach combining algorithmic concepts and

I am dealing with a json data in raw format that is unsorted. Here is a snippet of the data: [ { "level": 1, "id": 34, "name": "example-name", "father_id": 10 }, ... ] My goal is to o ...

ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When ...

What is the best way to extract items from another array that have approved IDs - is it through using map(), filter(),

I am unsure about the best approach to retrieve only the items (array with objects) that have been approved based on their id. Should I start by using map() and then filter(), or should I filter() them first and then map()? export class AppComponent { ...

Troubleshooting: Issue with reloading in MERN setup on Heroku

I successfully deployed my MERN stack application on Heroku using the following code: import express from "express"; import path from "path"; const app = express(); const port = process.env.PORT || 5000; app.get("/health-check&qu ...

Creating a dynamic form in Angular using reactive forms and form builder that pulls real-time data from the server

I have been struggling for the past two days to organize the data in the correct order but so far, I haven't been successful. Essentially, I retrieve some data from the server and present it to the client along with additional fields that the client n ...

I have encountered the same installation error with every Angular Masonry package I have tried to install on various applications

Every time I try to install one of the popular masonry packages for Angular, I encounter the same frustrating error. It's getting to the point where I feel like pulling my hair out. Unexpected token d in JSON at position 702 while parsing near ' ...

The problem arises when the Chrome extension fails to trigger the XRM JavaScript code execution

Utilizing the XRM JS APIs within Dynamics CRM is my goal as I develop a Chrome extension. The code snippet below demonstrates my current approach. chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) { chrome.scripting.executeScript({ ...

Using the Command Line Interface (CLI) to set up Angular 2 alongside

Hello everyone, I'm excited to share my first post! If you think I need to include any screenshots or code snippets, please let me know. I recently built a new application using the Angular 2 CLI. While I can successfully load data through mocks, I&a ...

Guide to implementing fullpagejs with Angular 7 selectors

I have been working on an Angular 7 project with fullpagejs by Alvarotrigo. Everything seems to be functioning properly, but I am facing an issue where the content of my website is not visible because the color of fullpagejs covers it all. When I use norma ...

Contrasting the utilization of `typeof` with a constant and `enum` in TypeScript

Can you explain the distinction between using typeof with a constant and an enum in TypeScript? For example: const TYPE_A = 'a' const TYPE_B = 'b' type MyType = | typeof TYPE_A | typeof TYPE_B type Result = { name: string type ...

Despite having installed v18.3, the Angular CLI specifically demands a minimum Node.js version of either v14.20, v16.14, or v18.10

Today I decided to upgrade my Angular CLI from v14.1 to v16. After upgrading, I encountered an issue every time I tried to run ng, which indicated that the CLI required a minimum version of node.js: The Angular CLI requires a minimum Node.js version of ei ...

Encountering a glitch when attempting to run Bootstrap 4 on an Angular 6 Application

After installing Bootstrap 4 using Angular CLI, I encountered an error when running the application. To resolve this issue, I made changes to the angular.json file: "styles": [ "src/styles.css", "../node_modules/bootstrap/dist/css/bo ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Identifying the unique parent component of a component within Angular

One of my components, named Com1, is imported into multiple other components. Within Com1, there is a button that triggers a function when clicked. In this function, I am trying to print out the parent component of the specific instance of Com1. How can I ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...