Is there a way to verify a user's login status?

Currently, I am working on an angular 13 project and incorporating @angular/fire 7 into my development process.

I have developed a service with various functions for injection. Below is the code snippet:

import { Injectable } from '@angular/core';
import {
  Auth,
  GoogleAuthProvider,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signInWithPopup,
  signOut,
  FacebookAuthProvider,
} from '@angular/fire/auth';
import { LoginData } from '../../shared/interfaces';

import { map, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  isLoggedIn$: Observable<boolean> | undefined;
  isLoggetOut$: Observable<boolean> | undefined;

  constructor(private afAuth: Auth) {
  }
  login( email: string, password : string ) {
    return signInWithEmailAndPassword(this.afAuth, email, password)
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }
  
}

While researching online, I came across a variable called authState which seems significant. However, I am unsure how to incorporate it within the context of angular/fire 7.

Answer №1

To retrieve the current user, utilize the Auth feature provided by @angular/fire/auth

Import { Auth } from '@angulat/fire/auth';

.... uid: string; constructor ( private auth: Auth ) {. this.uid = this.auth.currentUser.uid;

console.log('User logged in: ${this.uid}; }

Still anticipating documentation for querying Firestore collections and documents

Answer №2

you may try the following solution:

Check out this resource: https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#onauthstatechanged

 export class AuthService {
  constructor(public fireAuth: AngularFireAuth){
    this.checkAuthStatus();
  }

checkAuthStatus(){
  this.fireAuth.onAuthStateChanged((user)=>{
    if(user){
      console.log(user);
      console.log('User is logged in');
    }
    else{
      console.log('User is logged out');
    }
  })
}

When it comes to route guards, there are pre-built guards available:

https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md

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

Best Practices for Angular (2) Form Validation on the Server Side

Struggling to implement server-side form validation using Angular 2, specifically with the following setup: A basic form with login and password fields linked to the view via ngForm / ngModel directives Template-based form structure Synchronous validatio ...

Is it possible that an error is triggered when utilizing canActivate or canChildActivate?

A problem has arisen while using canActivateChild or canActivate in the child route. Despite working fine previously, an error is now being thrown: ERROR in src/app/app-routing.module.ts(8,7): error TS2322: Type '({ path: string; redirectTo: string; ...

Encountering difficulties installing npm bootstrap@3 within the Angular framework

Recently, I started learning Angular and decided to integrate Bootstrap into my Angular project. However, when I entered npm install --save bootstrap@3 into the terminal, the following warning messages were displayed: C:\Users\ssc\Angular-T ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

Browser not reflecting changes made to Angular 2 code

Currently facing a challenging issue with my express/angular2 app. Despite using nodemon and seeing the Express code updating fine, I am experiencing issues where my components and services are not updating when I reload the page in the browser. Even aft ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Issue with router navigation not functioning within an output event in Angular 4

I've encountered a situation with my table component where it emits an event containing an id. `@Output() onClick: EventEmitter<any> = new EventEmitter<any>();` `onRowClick(id: any) { this.onClick.emit(id); }` `<a href="#" (click ...

Error: Unable to access properties of null (specifically 'writeValue')

My goal is to retrieve an object by its ID, and if the object does not exist, the component will then register the object. However, when the object does exist, it retrieves the object normally, but then throws the same error again. HTML: <div class="c ...

Versatile typing capabilities

Is it possible to have a function that takes a configuration object as its parameter, specifying which properties in a data object should be read? The configuration object has two properties that correspond to keys in the data object. The configuration ob ...

Is there a way to access a file from an S3 bucket URL using Angular?

Currently, I have the URL but I'm not interested in putting in the effort to retrieve the file data or blob. This is my current approach: const url = 'https://s3-us-west-1.amazonaws.com/....'; const a: any = document.createElement('a& ...

Limiting the combinations of types in TypeScript

I have a dilemma: type TypeLetter = "TypeA" | "TypeB" type TypeNumber = "Type1" | "Type2" I am trying to restrict the combinations of values from these types. Only "TypeA" and "Type1" can be paired together, and only "TypeB" and "Type2" can be paired tog ...

Should Angular 6 developers consider storing JSON web tokens in LocalStorage or Session Storage?

After doing a lot of research, I have come across various discussions regarding the storing of JSON web tokens in different areas like local storage, session storage, and cookies. Each method has its own advantages and disadvantages that developers conside ...

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

Transform the `PascalCase` format into `strictCamelCase` in TypeScript type conversion

By utilizing the built-in Uncapitalize<S> function, you can easily convert a string like FooBar to fooBar: const fooBar: Uncapitalize<'FooBar'> = 'fooBar'; However, this method proves inadequate when dealing with class name ...

I'm encountering a 502 error while trying to use Supabase's signInWIthPassword feature

Despite all authentication functions working smoothly in my React, TypeScript, and Supabase setup, I'm facing an issue with signInWithPassword. In my context: I can successfully signIn, create a profile, and perform other operations like getUser() an ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Neither the child nor the parent are showing the ng-content

I'm working on a project with a child-parent structure and I have the following components: <app-parent> parent component <ng-content select=["parent"]></ng-content> <app-child></app-child> </app-par ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...