Angular Firebase Authentication: Simplifying User Authentication in Angular Apps

Tools I'm Utilizing

  • Angular 5
  • AngularFire5
  • Firebase & Firestore

Objective

I am working on developing a straightforward authentication/login and registration system. While I have already created one, I am facing some challenges and seeking the best approach to set up authentication.

Current Progress

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';

@Injectable()
export class AuthService {

  authState: any = null;
  email = '';
  username = '';
  password = '';
  errorMessage = '';
  error: {name: string, message: string} = {name: '', message: ''};

  constructor(private afAuth: AngularFireAuth, private router: Router) {
    this.afAuth.authState.subscribe((auth) => {
      this.authState = auth
    });
  }
  get isUserEmailLoggedIn(): boolean {
    if (this.authState !== null) {
      return true
    } else {
      return false
    }
  }
  get currentUser(): any {
    return (this.authState !== null) ? this.authState : null;
  }
  get currentUserId(): string {
    return (this.authState !== null) ? this.authState.uid : ''
  }

  // Other methods omitted for brevity
}

link.service.ts

import { Injectable, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

export interface Link { uid: string; url: string; shortURL: string; clicks: number }

@Injectable()
export class LinkService implements OnInit {
  url: string;
  shortURL: string;
  showAlert: boolean;
  links: Observable<any>;

  constructor(public authService: AuthService, private afs: AngularFirestore) {
        this.links = afs.collection('Links').valueChanges();
  }

  // Methods and logic removed for simplicity

}

Challenge Faced

In my implementation, I encountered an issue where I am unable to retrieve the currentUserID in the link.service.ts file as it returns undefined. However, the

this.authService.isUserEmailLoggedIn
function within the addLink() method works correctly. It's perplexing why it doesn't provide the correct value elsewhere.

Answer №1

Make sure to retrieve the ID in this manner.

 To fetch the ID, use the following code snippet:
          this.items = this.itemCollection.snapshotChanges().map(changes => {
            return changes.map(a => {
              const data = a.payload.doc.data();
              data.id = a.payload.doc.id;
              return data;
            });
          });

Answer №2

It is recommended to utilize the currentUserId() function like this:

'uid': this.authService.currentUserId(),

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

Checking for division by zero

I have a question about my calculator. I want to ensure that if the input string contains "0", an error alert is displayed. However, I do not want to check for the "/" character. Below is the function I have written: <input type="text" name="answer" ...

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

What could be the reason for the NODE_DEBUG=fs environment variable not working as expected?

According to the Node.js documentation on the fs module at https://nodejs.org/api/fs.html#fs_file_system: To obtain a trace back to the original call site, you can set the NODE_DEBUG environment variable: Here is an example of setting the fs environmen ...

What is the best way to import a file in meteor version 1.3?

Trying to incorporate react-datepicker into a meteor 1.3 and react project has been quite successful so far. The only issue I am facing is the inability to access any of the css styles from the package. According to the readme, I'm supposed to requir ...

What scenarios call for the utilization of setScriptTimeout?

When using Selenium WebDriver, there is a method called setScriptTimeout(time, unit). The description of this method states that it Specifies the time allowed for an asynchronous script to finish executing before an error is thrown. If the timeout is set ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Differences Between 'this' and 'self' in Classes

I am currently working with ES6 Classes and I'm struggling to grasp why I am able to access the this variable within one of the methods. //CODE class Form{ constructor(){ var self = this; } assemble(){ log(self); ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

Three.js - The initial child leaps into action and inherits the parent's transformations

I am currently working on establishing a parent/child hierarchy involving three objects using the ".add()" method in Three.js. When parenting two objects, everything works smoothly. However, I encountered an issue when trying to create a hierarchy with thr ...

What is the best way to terminate a file upload initiated by ajaxSubmit() in jQuery?

A snippet of code I currently have is: UploadWidget.prototype.setup_form_handling = function() { var _upload_widget = this; $('form#uploader') .unbind('trigger-submit-form') // Possibly a custom method by our company . ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

What is the best way to traverse through a nested JSON file with d3.js?

Greetings. I am currently facing a challenge in navigating through a nested JSON file. Below is the JSON data that I need assistance with: {"Id":466,"Name":"korea", "Occurrences": ...

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Advanced manipulation of scope in JavaScript

In order to ensure scope-busting for a specific listener in my application, I have implemented the following code: // within the prototype of MyClass var self = this; myElement.addEventListener("stuff", function(e){self.doStuff(e)}); By doing this, I am ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

The functionality of jQuery mouseenter and mouseleave events seems to be malfunctioning when applied to newly injected DOM elements

I encountered an issue with my code. It functions properly, but when I introduce new elements into the dom, it fails to show or hide them. jQuery("div.cat-icon").on({ mouseenter: function () { jQuery(this).find('.catselect').show( ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

converting a JSON array into an object

I seem to be facing a challenge: I have a JSON list with rows of data and a JSON object. My goal is to iterate through the list and assign the rows to different objects within the JSON structure. The first and last elements in the list are empty, followe ...