Using Firebase Database, Angular2 employs UID (User ID) as the primary key

Creating a signup component in my app using Firebase as the authentication method and database. After registering a new user, a key is generated and all user information, including the UID from authentication, is saved in the database. I want to use the UID from authentication as the primary key instead of the Firebase-generated key.

Here's the code snippet:

Component TypeScript file:

  signupUser(user: User) {
    this.firebaseAuth.auth
      .createUserWithEmailAndPassword(user.email, user.password)
      .then(value => {
        console.log('Success!', value);
        this.afdb.list('users').push({
          firstname: user.firstname,
          lastname: user.lastname,
          email: user.email,
          uid: value.uid
        });
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
      });
  }

JSON structure in Firebase:

users {
    -KpgNYJ0adjVyOGJiyBF {
        email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d58ca45c584bc8f84868">[email protected]</a>
        firstname: dasdsa
        lastname: dsadsads
        uid: 021oxk8X6rQL6gAfC0UhZpB4vZx2
        }
    }

Desired JSON structure:

users {
    021oxk8X6rQL6gAfC0UhZpB4vZx2 {
        email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3440475146324047514632054844484a">[email protected]</a>
        firstname: dasdsa
        lastname: dsadsads
        }
    }

Your assistance is greatly appreciated. Thank you.

EDIT: Forgot to mention that I'm using AngularFire2.

Answer №1

Replace push with update. When using push, a new node and unique key are created for that node. However, update either updates the specified node or creates it if it doesn't already exist.

registerUser(user: User) {
    this.firebaseAuth.auth.createUserWithEmailAndPassword(user.email, user.password)
    .then(value => {
	    console.log('Registration successful!', value);

        let userDetails = {
            first_name: user.first_name,
            last_name: user.last_name,
            email: user.email
        }

	    this.afdb.list('users').update(value.uid, userDetails);
    })
    .catch(err => {
	    console.log('Error:',err.message);
    });
}

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

Prevent resizing or zooming on AmCharts4 radar chart

Is there a way to disable the click-drag zooming feature on the AmCharts4 radar chart in my react application? Thank you. View image of the chart ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

Is there a way to align the mat card title and subtitle on a single line?

My code is utilizing Angular material and here is the HTML snippet: <mat-card> <mat-card-header *ngFor="let club of result[0]"> <mat-card-title>{{club.clubName}}</mat-card-title> <mat-card-subtitle>Clu ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

The webpage is functioning properly when accessed through localhost, but it is not working on Firebase or Netlify

Encountering a problem while trying to deploy my react app, even though I have successfully used firebase hosting in the past without any issues. Currently working on a simple news app using react, everything runs smoothly when testing it on localhost. H ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Error encountered during password reset in Auth0

I am currently working with Angular 2 and using lock version 10.8 in an attempt to implement a feature that allows users to change their password. I've been experimenting with the following method, which involves calling the Management API. In this me ...

Exploring Validations within Nested Forms in Angular

After grappling with this issue for a month, I am seeking any suggestions or advice. In my form pages, user input data is received. These pages include a component called basa-crud-page, which utilizes Template Driven Forms. The code snippets within this ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

Tips for properly defining path names in loadChildren for lazy loading in Angular 2 NgModules

When setting correct path names for loadChildren in the app-routing.module file within an Angular 2 NgModule, I encountered some issues. Despite following the NgModule concept outlined on the Angular main website, I still couldn't find clear informati ...

node.js + typescript How can we access instances from methods?

Following a server rebuild, the compiler creates an instance in the included API controller as shown below: NewController.ts import express = require("express"); import INew = require("../interface/INew"); import New ...

How come I'm able to access the form's control within setTimeout but not outside of it?

Having just started working with Angular, I came across a strange issue involving forms and setTimeout. When trying to access the form control of an input element inside setTimeout within the OnInit lifecycle hook, it works fine. However, when attempting t ...

Setting up Cypress.config file for SQL database testing with Cypress

Currently, I am looking to experiment with SQL databases. I have SqlWorkbench installed and have mysql added in my package file. However, I encountered an issue while attempting to run Cypress as SyntaxError: Unexpected token 'export' The probl ...

Angular Material: angular 4 alternative for detecting screen size greater than medium using $mdMedia('gt-md') function

Currently, I am working on integrating a sidenav into my web application with a focus on making it responsive. To accomplish this, I am utilizing Angular Material2 and Angular 4. <md-sidenav #sidenav layout="column" class="md-sidenav-left" md-component- ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

How can CSS variables be applied to a hover property within an Angular directive?

Check out the directive below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: 'd-btn', host: {} }) export class ButtonDirective { constructor(private el: ElementRef){} @HostLis ...

Creating a Chrome extension with Angular 5: A comprehensive guide

Currently, I am in the process of developing a Chrome extension using Angular 5. Initially, I successfully created a basic Angular app with the help of Angular Material and it functioned perfectly as an Angular application (I used ng build for verification ...